One: Parameter checking (using the @property adorner to turn the method into a property call is a method)
ClassStudent(object):@property #相当于get_score函数/getterdef score (self): return self._score @score. Setter #相当于set_score函数/setter def score (self, value): span class= "keyword" >if not isinstance (value, int): raise valueerror ( Span class= "string" > ' score must is an integer! ') if value < 0 or value > : raise valueerror ( ' score must between 0 ~ 100! ') Self._score = value
To turn a getter method into a property, just add @property
to it, and @property
itself creates another adorner @score. Setter
, which is responsible for turning a setter method into a property assignment
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!
You can also define read-only properties, define getter methods only, and do not define setter methods as a read-only property
class student @property def birth (self): return self._birth @birth. Setter def birth (self, value): Self._birth = value @property def age return 2015-self._birth
The above birth
is a read-write property, which age
is a readonly property
II: Multiple Inheritance (MixIn)
class Dog(Mammal, Runnable): pass
class Bat(Mammal, Flyable): pass
With multiple inheritance, a subclass can get all the functionality of multiple parent classes at the same time.
class Dog(Mammal, RunnableMixIn, CarnivorousMixIn): pass
MixIn的目的就是给一个类增加多个功能,这样,在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系。
Because Python allows multiple inheritance, mixin is a common design.
Only single-inherited languages, such as Java, are allowed to use the mixin design.
Python Day 9 (2) parameter check and multiple inheritance