Python learning Notes [7]--Object-oriented

Source: Internet
Author: User

Original link

1. Using __slots__:

__slots__ restricts dynamic binding to the current class. is limited to elements defined in __slots__ and is not bound for undefined elements. Returns an error.

class Student (object): ...      __slots__ = ('name' ' Age'#  Define the property names that are allowed to bind with a tuple ...
>>> s = Student ()#Create a new instance>>> S.name ='Michael' #binding Property ' name '>>> S.age = 25#binding attribute ' age '>>> S.score = 99#binding attribute ' score 'Traceback (most recent): File"<stdin>", Line 1,inch<module>Attributeerror:'Student'object has no attribute'score'

Because the property cannot be bound because it is ‘score‘ not placed __slots__ in, the score attempt to bind score will get attributeerror error.

It __slots__ is important to note that the __slots__ defined properties work only on the current class and do not work on inherited subclasses:

class graduatestudent (Student):      ... Pass ... >>> g = graduatestudent ()>>> G.score = 9999

Unless the module is also defined in a subclass, the module can also be inherited.

2. Using @property

When binding properties, if we directly expose the properties, although it is very simple to write, but there is no way to check the parameters, resulting in the result can be changed casually:

s == 9999

This is obviously illogical. To limit the scope of the score, you can set the score by one method, and set_score() then get the score by one, get_score() so that in the set_score() method, you can check the parameters:

classStudent (object):defGet_score (self):returnSelf._scoredefSet_score (self, value):if  notisinstance (value, int):RaiseValueError ('score must is an integer!')        ifValue < 0orValue > 100:            RaiseValueError ('score must between 0 ~ 100!') Self._score= value

Now, to operate on any of the student instances, you cannot set score as you wish:

>>> s = Student ()#  ok! >>> s.get_score ()60>>> S.set_score (9999) Traceback (most recent call last):  ~ 100!

However, the above method of invocation is slightly more complex, and it is not straightforward to use attributes directly.

Is there any way to access the variables of a class in such an easy manner as to check parameters and use similar properties? For the perfect Python programmer, this must be done!

Remember the adorner (decorator) can add functionality to a function dynamically? For class methods, adorners work as well. Python's built-in @property decorator is responsible for turning a method into a property invocation:

classStudent (object): @propertydefscore (self):returnself._score @score. Setterdefscore (self, value):if  notisinstance (value, int):RaiseValueError ('score must is an integer!')        ifValue < 0orValue > 100:            RaiseValueError ('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 ()#  OK, actual conversion to S.set_score#  OK, actual conversion to S.get_score () 60>>> s.score = 9999Traceback (most recent call last):  ~ 100!

Notice that this magical @property , when we operate on instance properties, we know that this property is probably not directly exposed, but is implemented through getter and setter methods.

You can also define read-only properties, define getter methods only, and do not define setter methods as a read-only property:

class Student (object):    @property    def  Birth (self):        return  self._ Birth    @birth. Setter    def  Birth (self, value):        = value    @property     def Age (self):         return 2014-self._birth

Python learning Notes [7]--Object-oriented

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.