Python Learning---Object-oriented advanced programming

Source: Internet
Author: User

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

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.