Replace the use of property getter and setter methods
@property
Become property functions, you can make the necessary checks on the property when the assignment, and to ensure a clear code short, there are two action
- The method of converting the read-only
- Attribute is set to achieve a re-reading method and, determines the boundaries do
class Money(object):
def __init__(self): self.__money = 0 @property def money(self): return self.__money @money.setter def money(self, value): if isinstance(value, int): self.__money = value else: print("error:不是整型数字")
operation result
In [3]: a = Money()
In [4]:
In [4]:
In [4]: a.money
Out[4]: 0 In [5]: a.money = 100 In [6]: a.money Out[6]: 100