19

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?

George
  • 988
  • 2
  • 10
  • 25

3 Answers3

30

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'
>>> 
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
7

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
shahvishal
  • 171
  • 4
1

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143