Discuss / Python / 子类实例允许定义的属性是自身的__slots__加上所有上级父类的__slots__(父类、父类的父类、父类的父类的父类。。。)

子类实例允许定义的属性是自身的__slots__加上所有上级父类的__slots__(父类、父类的父类、父类的父类的父类。。。)

Topic source

豆糕啊

#1 Created at ... [Delete] [Delete and Lock User]

验证:

class Student(object):
    __slots__=('name','age')
class GraduateStudent(Student):
    __slots__=('isGraduate','graduateDate')
class GraduateGender(GraduateStudent):
    __slots__=('gender', 'score')

#测试
s=GraduateGender()
s.score=20
s.gender='male'
s.isGraduate='True'
s.name='Lisa'

t=GraduateStudent()
t.gender='female'

#t.gender='female'报错,s.name='Lisa'没有报错
Traceback (most recent call last):
  File "d:/python3.8/class1.py", line 15, in <module>
    t.gender='female'
AttributeError: 'GraduateStudent' object has no attribute 'gender'

最后那个子类中使用slots的地方看不懂,看到你这个例子再理解一下懂了。

如果子类中没有__slots__字样,那么就会导致父类中的变量限制不起作用,除非子类中也进行了__slots__限制,那么就会继承父类的限制,结合自己的限制,形成新的限制。

有趣的是,如果子类继承自一个没有__slots__的父类,那么子类的__slots__限制不起作用。


  • 1

Reply