Python Day 9 (2) parameter check and multiple inheritance

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.