Python:删除子类中的类属性 [英] Python: deleting a class attribute in a subclass

查看:492
本文介绍了Python:删除子类中的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个子类,我想让它包含基类上存在的类属性。

I have a subclass and I want it to not include a class attribute that's present on the base class.

但它不工作:

>>> class A(object):
...     x = 5
>>> class B(A):
...     del x
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    class B(A):
  File "<pyshell#1>", line 2, in B
    del x
NameError: name 'x' is not defined

我该如何做?

推荐答案

仔细考虑为什么要这样做;你可能不会。考虑不要让B从A继承。

Think carefully about why you want to do this; you probably don't. Consider not making B inherit from A.

子类化的想法是专门化一个对象。特别地,类的子类应该是父类的有效实例:

The idea of subclassing is to specialise an object. In particular, children of a class should be valid instances of the parent class:

>>> class foo(dict): pass
>>> isinstance(foo(), dict)
... True

(用 x = property(lambda:AttributeError)),你打破了子类化概念,这是坏的。

If you implement this behaviour (with e.g. x = property(lambda: AttributeError)), you are breaking the subclassing concept, and this is Bad.

这篇关于Python:删除子类中的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆