George
George

Reputation: 1050

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?

Upvotes: 21

Views: 30374

Answers (3)

Robᵩ
Robᵩ

Reputation: 168626

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'
>>> 

Upvotes: 32

shahvishal
shahvishal

Reputation: 171

You can initialize the state of the Foo class from the Bar class and then append to the data like so:

class Foo(object):
    def __init__(self):
        self.data = "abc"

class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()
        self.data += "def"

When you instantiate an instance of Bar, the value of data that results is:

abcdef

Upvotes: 7

vaultah
vaultah

Reputation: 46533

You can refer to class variables of Foo from Bar's namespace via regular attribute access:

class Bar(Foo):
    data = Foo.data + 'def'

I don't know if it's a good practice, but there's no reason for it to be bad.

Upvotes: 1

Related Questions