python class and __slots__ @property

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011510825/article/details/80149360
  1. slots 
Assign string property names to order a special __slots__ class attribute, you can limit the instances of the class will be some legitimate set of attributes.
This is relatively simple, such as:

>>> class people(object):
...     __slots__ = ['age', 'name’]
Limits people only attribute age and name of.

Under comparison to know.
>>> class all(object):
…     pass

>>> a = people()
>>> b = all()
>>>
>>> a.age = 1
>>> a.age
1
>>> b.age = 2
>>> b.age
2
>>>
>>> a.gender = 'male'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'people' object has no attribute 'gender'
>>> b.gender = 'male'
>>> b.gender
'male'
First of age assignment, a, b are normal in gender assignment, a direct error, because people added __slots__ restrictions, only age and name instance properties.

__Slots__ why use it? Performance issues .
There are side effects of using __slots__

1. 每个继承的子类都要重新定义一遍__slots__
2. 实例只能包含哪些在__slots__定义的属性,这对写程序的灵活性有影响,比如你由于某个原因新网给instance设置一个新的属性,比如instance.a = 1, 但是由于a不在__slots__里面就直接报错了,你得不断地去修改__slots__或者用其他方法迂回的解决
So no more than examples million level classes, __ slots__ is not worth using, trouble ah, there is not conducive to others to read your code, not necessarily pythoner know this property ah, have to harm family google to find out.
PS: "fluent python" ruthless than I am, that's less than one million level instances are not worth using.


2.property 

When bound property, if we go directly to the property exposed, although it is very simple to write, however, no way to check the parameters that you can easily change the results:

class Student (object):
    pass

s = Student()
s.score = -1

This is very unreasonable, we need to do to score inspection parameters,
class Student (object):

    def get_score(self):
        return self._score

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

Now, for any instance of Student operation can not arbitrarily set the score:
>>> s = Student()
>>> s.set_score(60) # ok!
>>> s.get_score()
60
>>> s.set_score(9999)
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

But in fact, very troublesome, python idea is simple.

Python's built @property decorator is responsible for the property to become a method call

class Student (object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

@property implementation is more complex, let's look at how to use. To become a property getter method, only need to add @property on it at this time, @ property itself has created another decorator @ score.setter, is responsible for assigning attributes to become a setter method, so we have attributes a controlled operation.

Python's built @property decorator is responsible for the property to become a method invocation, it will become the property can not be changed.


Guess you like

Origin blog.csdn.net/u011510825/article/details/80149360