[英]How to add attribute to python *class* that is _not_ inherited?
I need to be able to set a flag on a class ( not on an instance of a class) which is not visible to a subclass. 我需要能够在子类不可见的类上 ( 而不是在类的实例上)设置标志。 The question is, is it possible, and how would I do it if it is?
问题是,是否可能,如果可以,我将如何做?
To illustrate, I want something like this: 为了说明,我想要这样的东西:
class Master(SomeOtherClass):
__flag__ = True
class Child(Master):
pass
... where hasattr(Master, "__flag__")
should return True
for Master
but False
for Child
. ...
hasattr(Master, "__flag__")
对于Master
应该返回True
,对Child
应该返回False
。 Is this possible? 这可能吗? If so, how?
如果是这样,怎么办? I don't want to have to explicitly set
__flag__
to false in every child. 我不想在每个孩子中都将
__flag__
显式设置为false。
My initial thought was to define __metaclass__
, but I don't have the luxury of doing that because Master
inherits from some other classes and metaclasses I don't control and which are private. 我最初的想法是定义
__metaclass__
,但是我没有这样做的奢侈之处,因为Master
继承__metaclass__
不控制的其他一些类和元类,它们是私有的。
Ultimately I'm wanting to write a decorator so that I can do something like: 最终,我想编写一个装饰器,以便可以执行以下操作:
@hide_this
class Master(SomeOtherClass): pass
@hide_this
class Child(Master): pass
class GrandChild(Child): pass
...
for cls in (Master, Child, GrandChild)
if cls.__hidden__:
# Master, Child
else:
# GrandChild
You were very close: 您非常接近:
class Master(SomeOtherClass):
__flag = True
class Child(Master):
pass
Two leading underscores without trailing underscores invokes name mangling , so the attribute will be named _Master__flag
. 两个前导下划线而不尾随下划线调用名称
_Master__flag
,因此该属性将命名为_Master__flag
。 Therefore if you check: 因此,如果您检查:
hasattr(cls, '_{}__flag'.format(cls.__name__))
it will only be True
for Master
, not Child
. 这对
Master
才是 True
的,对Child
不然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.