Discuss / Python / 【Question】只把__slots__放到子类里面,似乎不work

【Question】只把__slots__放到子类里面,似乎不work

Topic source

class Animal(object): def run(self): print('Animal is running!')

class Cat(Animal): slots = ('weight', 'height')

cat = Cat() cat.weight = 100 cat.tall = 90

这个代码是不会报错的(slots限制没有work),并且能看到实例cat里面有tall这个属性。。。

dir(cat) [........ 'height', 'run', 'tall', 'weight']

同样的代码,在Animal里面加了slots的变量以后,cat的属性就可以被slots限制住了

class Animal(object): slots=() def run(self): print('Animal is running!')

class Cat(Animal): slots = ('weight', 'height')

cat = Cat() cat.weight = 100 cat.tall = 90

line 12, in <module> cat.tall = 90 AttributeError: 'Cat' object has no attribute 'tall'

请问一下这是什么原因?

第一种:父类没限制,子类限制,结果就是没限制。因为子类限制的区域是:父类限制的范围+子类限制的范围,虽然子类限制比如只能输入1,2,但是你父类可以输入任意数,并集就是 父子2个都可以输入任意数,文章结尾有一句话是:子类实例允许定义的属性就是自身的slots加上父类的slots 。第二种:父类什么都不能输入,子类可以输入weight, height 那么子类范围就是: 空 + weight, heigh,所以tall会报错,因为父子都没说可以输入tall。

JOIEUH

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

有点‘并集’的意思


  • 1

Reply