Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change parent attribute in subclass python

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?

like image 998
George Avatar asked Nov 18 '15 16:11

George


People also ask

Can subclasses override attributes?

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.

How do you call a parent attribute in Python?

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.

Do subclass inherit attributes?

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.

What is __ Init_subclass __ in Python?

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().


1 Answers

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'
>>> 
like image 125
Robᵩ Avatar answered Oct 13 '22 10:10

Robᵩ