- Everything is an object, whether it is a class or an instance.
- Python is a strong dynamic language, and Java differs in this regard.
class Ab(): a = 666# 定义类对象Ab,自带属性a,值为666# 使用Ab.__dict__可以查看类Ab的属性us1 = Ab()us2 = Ab()# 定义两个实例对象us1、us2,这两个实例自身并不具备任何属性# 只有在__init__中定义了self.arg=xxx的情况下,实例默认会具备arg属性
- In a dynamic language, a property comes with an action method: Get (Read), set (write), or define a delete
print(Ab.a, us1.a, us2.a)# 获取属性a,输出均为666# 属性查找机制:自下而上。# python查找对象us1不具备属性a,就会在其所属的类对象Ab中查找属性a。us1.a += 333# 输出999# 首先查找us1.a未找到,于是使用Ab.a# 然后设置Ab.a+333的值为us1.a属性的值Ab.a += 222# 输出888print(Ab.a, us1.a, us2.a)# 输出分别为888,999, 888# us1已具备属性a,值为999.所以不再类中查找# us2不具备属性a,所以使用类Ab.a的值
@property
Change the method of a class to a property
Reason:
The property can be read and written without using the method restriction attribute;
Using methods to restrict read and write, it is cumbersome to read and write (to invoke three methods: Get, set, Del)
Workaround: Decorator Property
Converts a method to a property, which is convenient to call and prevents arbitrary changes.
- Example
class Student(object): @property def score(self): ‘‘‘ 原本定义为get_score() 调用方法:xiaopang.get_score() 如今调用属性score:xiaopang.score ‘‘‘ return self._score @score.setter def score(self, value): ‘‘‘ 原本定义为set_score() 调用方法:xiaopang.set_score(80) 如今调用属性score:xiaopang.score = 80 ‘‘‘ if not isinstance(value, int): raise ValueError(‘score must be an integer!‘) if value < 0 or value > 100: raise ValueError(‘score must between 0 ~ 100!‘) self._score = value
- Property principle
- The property is not directly exposed, but it is passed by the getter and setter method.
- Dir (property) See also Deleter method, if only getter (default), no setter, the attribute is read-only
Python learns the attributes of such and instances; adorner @property