[英]Python - Why can't attributes of inherited object be deleted?
Why can't attributes of inherited object be deleted? 为什么不能删除继承对象的属性?
class A(object):
def delete(self):
pass
def dont_delete(self):
pass
class B(A):
pass
del A.delete
del B.dont_delete
AttributeError: dont_delete
dont_delete
is not copied over to B
; dont_delete
不会复制到B
; you can only delete direct attributes from objects. 您只能从对象中删除直接属性 。
Python looks up attributes on instances and classes by delegating down the chain of inheritance, not by copying attributes across to sub-classes. Python通过委派继承链来查找实例和类上的属性,而不是将属性复制到子类中。 As such there is nothing to delete from a subclass either.
因此,也没有要从子类中删除的内容。
You should not try and 'uninherit'; 您不应该尝试“取消继承”; when are using
A
as a base class, you are effectively stating that B
is the same thing as A
, only more specialised. 当使用
A
作为基类时,您实际上是在说B
与A
是同一件事,只是更加专业。 That process only ever should add attributes, not remove. 该过程只能添加属性,不能删除属性。 Design your classes accordingly;
相应地设计课程; use a mixin base class for attributes and methods that should not always be inherited, for example.
例如,将mixin基类用于不应总是被继承的属性和方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.