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
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With