python面向对象编程高级篇__slots__ @property 多重继承

python语言中我们可以随时给实例增加新的属性和方法

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

分别增加了一个属性'name' 方法 set_age() 附带增加属性age

注意 只是对当前实例有效,其他实例无效

__slots__关键字

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'

注意:对当前类实例起作用,对继承的子类是不起作用的

@property关键字

使得score方法作为属性调用,这样避免属性的直接暴露,而通过间接方法getter和setter实现,虽然可能在类外直接看不到。当然如果没有setter方法的话,那么属性就是只读的。

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

多重继承

一个子类可以继承多个父类,以及多个方法;可以更快捷的进行组织。

__str__()和__repr__()打印实例

>>> 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__()和__next__()返回迭代对象用于for循环

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)

参考来源:https://www.liaoxuefeng.com/wiki/1016959663602400/1017590712115904

猜你喜欢

转载自blog.csdn.net/li4692625/article/details/109502419