繁体   English   中英

如何将_not_继承的属性添加到python * class *?

[英]How to add attribute to python *class* that is _not_ inherited?

我需要能够在子类不可见的类上而不是的实例上)设置标志。 问题是,是否可能,如果可以,我将如何做?

为了说明,我想要这样的东西:

class Master(SomeOtherClass):
    __flag__ = True

class Child(Master):
    pass

... hasattr(Master, "__flag__")对于Master应该返回True ,对Child应该返回False 这可能吗? 如果是这样,怎么办? 我不想在每个孩子中都将__flag__显式设置为false。

我最初的想法是定义__metaclass__ ,但是我没有这样做的奢侈之处,因为Master继承__metaclass__不控制的其他一些类和元类,它们是私有的。

最终,我想编写一个装饰器,以便可以执行以下操作:

@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

您非常接近:

class Master(SomeOtherClass):
    __flag = True

class Child(Master):
    pass

两个前导下划线而不尾随下划线调用名称 _Master__flag ,因此该属性将命名为_Master__flag 因此,如果您检查:

hasattr(cls, '_{}__flag'.format(cls.__name__))

这对Master 才是 True的,对Child不然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM