您的位置:首页 > 编程语言 > Python开发

python3中使用__slots__限定实例属性操作分析

2020-04-26 07:05 120 查看

本文实例讲述了python3中使用__slots__限定实例属性操作。分享给大家供大家参考,具体如下:

正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。先定义class:

# 类定义
class Person(object):
pass

然后,尝试给实例绑定一个属性:

p = Person()
p.name = "jadeshu"
print(p.name)

输出:

jadeshu

还可以尝试给实例绑定一个方法:

# 类定义
class Person(object):
pass
p = Person()
p.name = "jadeshu"
print(p.name)
def set_age(self, age): # 定义一个函数作为实例方法
self.age = age
from types import MethodType
p.set_age = MethodType(set_age, p)
p.set_age(25)
print(p.age)

输出:

jadeshu
25

但是,给一个实例绑定的方法,对另一个实例是不起作用的:

p2 = Person() #创建新的实例
p2.set_age(25) #调用方法

出错:

Traceback (most recent call last):
25
  File "C:/Users/Administrator/Desktop/PycharmProjects/test.py", line 48, in <module>
    p2.set_age(25)
AttributeError: 'Person' object has no attribute 'set_age'

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

def set_score(self, score):
self.score = score
Person.set_score = set_score
p.set_score(80)
print(p.score)

输出:80

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

p.set_score(80)
p2 = Person()
p2.set_score(100)
print(p.score)
print(p2.score)

输出:

80
100

通常情况下,上面的set_score方法可以直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能,这在静态语言中很难实现。

使用__slots__

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

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

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

然后,我们试试:

>>> s = Person() # 创建新的实例
>>> s.name = 'jadeshu' # 绑定属性'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'

由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。

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

>>> class Student(Person):
...   pass
...
>>> s = Student()
>>> s.score = 9999

除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息