Python allows you to define a special __slots__ variable when defining a class to limit the attributes that the class instance can add:
class Student(object): __slots__ = (‘name‘, ‘age‘) # 用tuple定义允许绑定的属性名称
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。
Python's built-in @property decorator is responsible for turning a method into a property invocation:
class student (object): @ Property def scorereturn self._score @score. Setter def score (self, value): if not isinstance (value, int): raise valueerror (if value < 0 or value > : raise valueerror ( ' score must between 0 ~ 100! ') Self._score = value
@propertyImplementation is more complex, we first examine how to use. To turn a getter method into a property, just add it, and @property at this point, it @property creates another adorner @score.setter , which is responsible for turning a setter method into a property assignment, so we have a controllable property operation:
>>> s = Student()>>> s.score = 60 # OK,实际转化为s.set_score(60)>>> s.score # OK,实际转化为s.get_score()60>>> s.score = 9999Traceback (most recent call last): ...ValueError: score must between 0 ~ 100!
The purpose of MixIn is to add multiple functions to a class, so that when designing a class, we prioritize the ability to combine multiple MixIn with multiple inheritance, rather than designing complex, hierarchical inheritance relationships.
class Dog(Mammal, RunnableMixIn, CarnivorousMixIn): pass
Python Learning---Object-oriented advanced programming