1. Class Properties
-
1.1 Definitions
- An outer class method
属性名 = 属性值
defined attributes - interview method:
类名.属性名
对象名.属性名
class Student: cls_id = 102 stu = Student() print(Student.cls_id) print(stu.cls_id) print("---------") Student.cls_id = 103 print(Student.cls_id) print(stu.cls_id) print("---------") stu.cls_id = 104 print(Student.cls_id) print(stu.cls_id)
operation result:
102 102 --------- 103 103 --------- 103 104
- An outer class method
-
1.2 the difference between the object and the class attribute properties
- (1) different numbers in memory
- Object properties: the number of objects created, how many there are in memory
- Attribute class: class exists only in memory there is only one, but the object can be read
- (2) define different positions
- Object attributes: the class defined in the method
- Attribute class: class methods defined within an outer
- Different (3) access method
- Object properties:
对象名.属性名
- Class properties:
类名.属性名
- Read class attribute, by
对象名.属性名
- Read class attribute, by
- Object properties:
- (4) different life cycle
- Object Properties: Create Object -> Object recovered by the system
- Class properties: Load the global namespace -> End program
- (5) Different owner
- Object Properties: objects belonging
- Class Attribute: belong to the class
- (1) different numbers in memory
2. static method
- A class method: Concepts
- Format: In the method of adding the above
@staticmethod
- Parameters: You can have parameters, no parameters
- And the code is generally used regardless of the class of objects, and the object instance: application scenario
- Use:
- (1)
类名.类方法名
- (2)
对象名.类方法名
- (1)
- Example usage scenarios:
- Such as: the main menu to show student management system
3. Class Methods
- The concept: no method can be called directly by the class instantiation
- Format: In the method of adding the above
@classmethod
- Parameters: first argument must be received class itself
- Parametric methods for cls can also be other names, but generally the default is cls
- cls class object point (i.e. below examples Goods)
- Scenario: When a process involving only static methods can use the class attributes (attribute-based method is used to modify the class)
- Use:
- (1)
对象名.类方法名
- (2)
类名.类方法名
- (1)
- Example usage scenarios:
- Modify discount on all merchandise
class Goods(): discount = 1 def __init__(self,price,name): self.name = name self.price = price def price_discount(self): return self.price * Goods.discount @classmethod def change_discount(cls,new_discount): cls.discount = new_discount goods = Goods(20, "audi") print(goods.price_discount()) Goods.change_discount(0.5) print(goods.price_discount())
The result: 20 10.0
- Modify discount on all merchandise