python限定类属性的类属性:__slots__

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python限定类属性的类属性:__slots__相关的知识,希望对你有一定的参考价值。

__slots__
由于Python是动态语言,任何实例在运行期都可以动态地添加属性。

如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。

顾名思义,__slots__是指一个类允许的属性列表:

class Student(object):
    __slots__ = (‘name‘, ‘gender‘, ‘score‘)
    def __init__(self, name, gender, score):
        self.name = name
        self.gender = gender
        self.score = score
现在,对实例进行操作:

>>> s = Student(‘Bob‘, ‘male‘, 59)
>>> s.name = ‘Tim‘ # OK
>>> s.score = 99 # OK
>>> s.grade = ‘A‘
Traceback (most recent call last):
  ...
AttributeError: ‘Student‘ object has no attribute ‘grade‘
__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。
 

 

 
class Person(object):

    __slots__ = (‘name‘, ‘gender‘)

    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

class Student(Person):

    __slots__ = (‘score‘,)

    def __init__(self,name,gender,score):
        super(Student,self).__init__(name,gender)
        self.score=score

s = Student(‘Bob‘, ‘male‘, 59)
s.name = ‘Tim‘
s.score = 99
print s.score

以上是关于python限定类属性的类属性:__slots__的主要内容,如果未能解决你的问题,请参考以下文章

python3之类的 __slots__ 属性

Python面向对象高级编程-__slots__定制类,枚举

类中的__slots__方法与__dict__方法相排斥

Python内置函数__slots__

python----03(面向对象进阶02)

python中函数和方法区别,以及如何给python类动态绑定方法和属性(涉及types.MethodType()和__slots__)