简体   繁体   中英

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 . Is this possible? If so, how? I don't want to have to explicitly set __flag__ to false in every child.

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.

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 . Therefore if you check:

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

it will only be True for Master , not Child .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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