I have the following class
class Foo():
data = "abc"
And i subclass it
class Bar(Foo):
data +="def"
I am trying to edit a parent class attribute in subclass. I want my parent class to have some string, and my subclass should add some extra data to that string. How it should be done in Python? Am i wrong by design?
A subclass “inherits” all the attributes (methods, etc) of the parent class. This means that a subclass will have everything that its “parents” have. You can then change (“override”) some or all of the attributes to change the behavior. You can also add new attributes to extend the behavior.
Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.
A subclass “inherits” all the attributes (methods, etc) of the parent class. We can create new attributes or methods to add to the behavior of the parent We can change (“override”) some or all of the attributes or methods to change the behavior.
The __init_subclass__ class method is called when the class itself is being constructed. It gets passed the cls and can make modifications to it. Here's the pattern I used: class AsyncInject: def __init_subclass__(cls, **kwargs): super().
You ask two questions:
How it should be done in Python?
class Bar(Foo):
data = Foo.data + "def"
Am i wrong by design?
I generally don't use class variables in Python. A more typical paradigm is to initialize an instance variable:
>>> class Foo(object):
... data = "abc"
...
>>> class Bar(Foo):
... def __init__(self):
... super(Bar, self).__init__()
... self.data += "def"
...
>>> b = Bar()
>>> b.data
'abcdef'
>>>
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