Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 742
Bryan Oakley Avatar asked Jun 19 '15 18:06

Bryan Oakley


People also ask

How do I add an attribute to a class in Python?

Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.

How do you inherit a class attribute in Python?

Use the super() Function By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

Can you inherit attributes Python?

Inheritance is the capability of one class (child/derived/sub class) to derive or inherit the properties or attributes from some another class (parent/base class) . Inheritance increases reusability of a code. We don't need to write the same code again and again.

Can class attributes be inherited?

Objects are defined by classes, classes can inherit attributes and behavior from pre-existing classes. The resulting classes are known as derived classes or subclasses. A subclass “inherits” all the attributes (methods, etc) of the parent class.


1 Answers

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.

like image 128
jonrsharpe Avatar answered Oct 13 '22 00:10

jonrsharpe