Python 之 高级面向对象编程 slots

来源:互联网 发布:网络新技术论文 编辑:程序博客网 时间:2024/05/15 18:44

本文转载自微信公众号Python互动中心

面向对象高级编程技术

数据封装、继承和多态是面向对象程序设计中的三个基本概念,另外还有很多特征,包括多重继承和定制类。

使用slots()

在Python中,可以对类动态的增加属性和方法,这是在静态语言中很难实现的。

from types import MethodTypeclass Student(object):    def __init__(self):        print('Instance Created')Tracy = Student()Tracy.age = 20Bob = Student()Bob.age = 30print('Tracy\'s age is %d'%Tracy.age)print('Bos\'s age is %d'%Bob.age)def set_age(self,age):    self.age = ages = Student()s.set_age = MethodType(set_age,s)s.set_age(25)print(s.age)Ceaser = Student()Student.set_age = set_ageCeaser.set_age(33)print('Ceaser\'s age is %d'%Ceaser.age)


这也带来了一个问题,属性和方法可以随意更改,如果想要增加限制可以使用__slots__。

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

使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类不起作用。

from types import MethodTypeclass Student(object):    def __init__(self):        print('Instance Created')    __slots__= ('name','age','set_age') #用tuple定义允许绑定的属性名称Tracy = Student()Tracy.age = 20Bob = Student()Bob.age = 30print('Tracy\'s age is %d'%Tracy.age)print('Bos\'s age is %d'%Bob.age)def set_age(self,age):    self.age = ages = Student()s.set_age = MethodType(set_age,s)s.set_age(25)print(s.age)Ceaser = Student()Student.set_age = set_ageCeaser.set_age(33)print('Ceaser\'s age is %d'%Ceaser.age)Ceaser.score = 99print('Ceaser\'s score is %d'%Ceaser.score)

__slots__ = ('name','age','set_age')但是没有score,所以会报错AttributeError

使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类不起作用。




原创粉丝点击