Daily Drinks: The richest person in the world is the one who falls the most; the bravest person is the one who can stand up every time he falls; the most successful person is the one who can not only stand up every time he falls, but also keep going.
Start learning
class
Define class keyword class
init is a special method for creating objects that can be written or not written when initialization is not used
Say something with examples 1
class tyler(object): # Class can also create class tyler without writing object (inheriting object by default): def __init__ (self,name,age): self.name = name self.age = age def study(self,course): self.course = course print('%s I am learning%s. '%(self.name,self.course)) def watch(self): if self.age <18: print('%s You can only watch The Bear Comes Out'%self.name) else: print('%s You can only watch Action Movie.'%self.name) if __name__ == "__main__": stu = tyler('asd',19) #The () here takes the initialization _init_ function, which has two parameters, so it needs to be assigned. stu.watch() # Call functions in classes
You can also call it here with the main () function
def main(): #Create student objects and specify names and ages stu1 = tyler('Colored glaze', 38) # Send study messages to objects stu1.study('Pytho') # Send a watch_av message to the object stu1.watch() stu2 = tyler('Glass door', 15) stu2.study('Read a Book') stu2.watch() if __name__ == '__main__': main()
Say something with examples 2
class student: # When your class has some common variables, you can initialize them. def __init__(self,name): # In the second class, all variables and functions must be self-imprinted. self.name = name def def1(self,num): self.num = num print(self.num) print(self.name) def def2(self): print(self.name) print(self.num) if __name__ == "__main__": stu = student('Li Si') #() It's the initialization function. stu.def1(100) stu.def2()
Practice
Read the TXT file and output how many uppercase letters are there
class tyler(object): def __init__(self): self.count = 0 pass def reada(self): with open ('C:/Users\\a\\Desktop\\ds.txt',mode='r') as f: lines = f.read() for line in lines: new_line = line.strip('\n') # print(new_line,end="") for i in new_line: if i.isupper(): self.count +=1 print('Number of capital letters%d'%self.count) if __name__ == "__main__": T = tyler() T.reada()
Visibility issues
Variables, functions can be called in classes, and functions can also be called in functions.
Private variable with''before the variable name
If you have to use private variables, you can use dir (class ()) to see his real name.
Private variables or functions that can be called directly within a class
If you want to represent a variable or function, you can use''
Talk about things by topic
class test: def __init__(self,foo): self.__foo = foo #private variable def __bar(self): print(self.__foo) print('__bar') if __name__ == "__main__": ts = test("hello") #AttributeError: 'test' object has no attribute '__bar' ts._test__bar() #Call with a private full name
@ porperty decorator
# The name of the function that converts a function into an attribute modifier and an accessor should be the same
# If you want to access private attributes, you can use the getter (accessor) and setter (modifier) methods of attributes to do the corresponding operations.
Consider using the @property wrapper to wrap getter and setter methods
# To put it bluntly, you can modify private variables with a decorator
class person (object): def __init__(self,name,age): self._name = name self._age = age #Accessor - getter method @property def name(self): return self._name #Accessor - getter method @property def age (self): return self._age #Modifier -- setter method @age.setter def age(self,age): self._age = age def play(self): if self._age <16: print('%s Playing games'%self._name) else: print('%s Reading a Book'%self._name) if __name__ == "__main__": per = person('Zhang San',45) per.play() per.age = 10 #Modifiable private variables per.play()
slots, magic
If we need to qualify objects of custom types that can only bind certain properties, we can qualify them by defining _slots_ variables in the class. It should be noted that the _slots_ restriction only works on the object of the current class and does not work on subclasses.
class person (object): #Limit the person object to bind only _name,_age,_gender attributes __slots__ = ('_name','_age','_gender') def __init__(self,name,age): self._name = name self._age = age @property def name(self,name): return self._name @property def age(self): return self._age @age.setter def age(self,age): self._age = age def play(self): if self._age <16: print('%s Playing flying chess.' % self._name) else: print('%s Playing with the landlord.' % self._name) if __name__ == "__main__": per = person('May you stay forever young',23) per.play() per._gender = 'male'
Static Method and Class Method
#Use @static method from math import sqrt class calss_a(object): def __init__(self, a, b, c): self._a = a self._b = b self._c = c @staticmethod def is_valid(a, b, c): return a + b > c and b + c > a and a + c > b def perimeter(self): return self._a + self._b + self._c def area(self): half = self.perimeter() / 2 return sqrt(half * (half - self._a) * (half - self._b) * (half - self._c)
def main(): a, b, c = 3, 4, 5 # Static methods and class methods are invoked by sending messages to classes if calss_a.is_valid(a, b, c): t = calss_a(a, b, c) print(t.perimeter()) # You can also call an object method by sending a message to a class, but pass in the object receiving the message as a parameter. # print(Triangle.perimeter(t)) print(t.area()) # print(Triangle.area(t)) else: print('Can't form a triangle.') if __name__ == '__main__': main()
inherit
In addition to inheriting the attributes and methods provided by the parent class, the subclass can also define its own unique attributes and methods, so the subclass has more capabilities than the parent class.
class person (object): def __init__(self, name, age): self.name = name self.age = age def play(self): print('%s Playing happily.' % self.name) def watch(self): if self.age >= 18: print('%s Watching love action movies.' % self.name) else: print('%s You can only watch "The Bear Comes Out".' % self.name) class student(person): def __init__(self, name, age, grade): super().__init__(name, age) self._grade = grade @property def grade(self): return self._grade @grade.setter def grade(self, grade): self._grade = grade def study(self, course): print('%s Of%s I am learning%s.' % (self._grade, self.name, course)) if __name__ == "__main__": stu = student('Daniel',15,'Junior') stu.study('Mathematics')