python面向对象高级编程

1.绑定方法

给所有实例都绑定方法,可以给class绑定方法:

>>> def set_score(self, score):

... self.score = score

...

>>> Student.set_score = set_score

给class绑定方法后,所有实例均可调用。

2.使用__slots__

但是,如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加nameage属性。

为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性。

class Student(object):

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

猜你喜欢

转载自www.cnblogs.com/zhouqianwei/p/9154451.html