-
又一个非常方便的Python语法特性
class Product: def __init__(self, value): self.price = value @property def price(self): return self.__price @price.setter def price(self, value): if value < 0: raise ValueError self.__price = value
我们使用@property修饰方法,此时会把方法直接变成同名属性。当我们获取属性的值时,实际上就是调用的此方法。
此时,本身又自动创建了另一个装饰器,负责把一个方法变成属性赋值,即:price的setter方法。于是,修饰的其实是,当我们给price赋值时,实际上就是调用的此方法。此时,price对外表现得就像一个普通的attribute
- 继承
class Animal: def __init__(self): self.age = 1 def eat(self): print('eat') class Mammal(Animal): def walk(self): print('walk') m = Mammal() print(m.age) # 1 m.eat() # eat print(isinstance(m, object)) # True print(issubclass(Mammal, Animal)) # True
所有的类都直接或者间接继承自 object 类