How to change parent attribute in subclass python How to change parent attribute in subclass python python python

How to change parent attribute in subclass python


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


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


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.