Python member of the class, members of the members of the special modifiers, and the like.
Python class members
Members of the class can be divided into three categories: field, methods and properties.
1 # Note: All members, only the contents of the general field of preservation object, namely: 2 # according to the number of objects created such, there are that many common fields in memory. 3 # and other members, it is stored in the class, that is: no matter how many objects, only one copy is created in memory.
First, the field
Fields include: general fields and static fields, they differ in the definition and use, and the most essential difference is stored in a different memory location,
- Ordinary objects belonging to the field
- Static field belongs to the class
class Student: # static field LOCATION = ' China ' # initialization, also known as the constructor DEF __init__ (Self, name, Age): self.name = name self.age = Age # direct access to the general field STU = Student ( ' Steven ' , 16 ) stu.name # direct access to static fields Student.location # (class name. field name) stu.location # (object name. field name)
Ordinary fields need to be accessed through the object
static field not only, also can be accessed through the object access through the class
but common ownership of fields and static fields are different. Which is similar to the following in the storage contents:
But from the figure:
- Static fields in memory to save only one copy
- In the general field should save a copy of each object
Scenario: When the class by creating an object, if each object has the same field, then use the static field
Second, the method
Methods include: general methods, static methods and class methods, three methods all belong to the class in memory, the difference lies in the different ways to call.
Common methods : invoked by an object; at least one self parameter; when an ordinary method, the object of the method automatically calls assigned to the self;
class methods : a class called; at least one cls parameter; performing class methods automatically invoke the method copy to class cls;
static methods : by the class call; no default parameters;
Import Time class timetest (Object): DEF the __init__ (Self, year, month The, Day): self.year = year self.month = month The self.day = Day DEF Trans (Self): # conventional method return self.year, Self .month, self.day @classmethod # class method DEF Check (CLS, str_time): '' ' string determines whether the input valid date ' '' the receive = CLS (* str_time.split ( ' , ' )) iF int(receive.year) > 0 and (0 <= int(receive.month) <= 12) and (0 <= int(receive.day) <= 31): return receive.trans() else: print('字符串日期不合法!') @staticmethod #静态方法 def showtime(): return time.strftime('%H:%M:%S', time.localtime())
t = TimeTest(2019, 1, 1) nowTime = t.showtime() print(nowTime) print(t.check('2018,12,31')) #结果 22:07:10 ('2018', '12', '31')