当前位置:首页 > Python教程 > python技巧

Python实例属性限制(__slots__)

Python的动态绑定可以在程序运行的过程中对实例或class加上功能,但是如果我们想要限制实例的属性怎么办呢?更改内容请参考:Python学习指南

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

                
                    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
            

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

                s2 = Student()  #创建一个新的实例
s2.set_age(25)
Traceback (most recent call last):
  File "<stdin>", line 1, in<module>AttributeError: 'Student'object has no attribute 'set_age'
            

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

                
                    def set_score(self, score):  
    self.score = score
Student.set_score = set_score
            

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

                s.set_score(100)
s.score
100
s2.set_score(99)
s2.score
99
            

只要在class上绑定方法以后,实例就可以直接使用了。

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

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

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

                
                    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'>>>Student.score =100>>>s.score
100
            

由于‘score‘没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。但是可以对class类添加属性,__slots__只是限制实例添加的属性,但类属性管不了。

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

                
                    class GraduteStudent(Student):
    pass
g = GraduteStudent()
s.score =99
            

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

原文:https://www.cnblogs.com/miqi1992/p/8342946.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐