Python object-oriented programming advanced chapter __slots__ @property multiple inheritance

In the python language, we can add new attributes and methods to the instance at any time

class Student(object):
    pass
>>> s = Student()
>>> s.name = 'Michael' # 动态给实例绑定一个属性
>>> print(s.name)
Michael

>>> def set_age(self, age): # 定义一个函数作为实例方法
...     self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25

Added an attribute'name' method set_age() with added attribute age

Note that it is only valid for the current instance, and invalid for other instances

__slots__ keyword

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称

>>> s = Student() # 创建新的实例
>>> s.name = 'Michael' # 绑定属性'name'
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

Note: It works on the current class instance, but does not work on inherited subclasses

@property keyword

Make the score method called as a property, so as to avoid the direct exposure of the property, and realize it through the indirect method getter and setter, although it may not be seen directly outside the class. Of course, if there is no setter method, then the property is read-only.

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

Multiple inheritance

A subclass can inherit multiple parent classes and multiple methods; it can be organized more quickly.

 

__str__() and __repr__() print examples

>>> class Student(object):
...     def __init__(self, name):
...         self.name = name
...     def __str__(self):
...         return 'Student object (name: %s)' % self.name

        __repr__ = __str__
#print打印实例,调用__str__

>>> print(Student('Michael'))
#直接显示实例,调用__repr__
>>> s = Student('Michael')
>>> s

__iter__() and __next__() return iteration objects for for loops

class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1 # 初始化两个计数器a,b

    def __iter__(self):
        return self # 实例本身就是迭代对象,故返回自己

    def __next__(self):
        self.a, self.b = self.b, self.a + self.b # 计算下一个值
        if self.a > 100000: # 退出循环的条件
            raise StopIteration()
        return self.a # 返回下一个值
>>> for n in Fib():
...     print(n)

Reference source: https://www.liaoxuefeng.com/wiki/1016959663602400/1017590712115904

Guess you like

Origin blog.csdn.net/li4692625/article/details/109502419