How to change parent attribute in python subclass

I have the following class

class Foo():
    data = "abc"

And a subclass of this class

class Bar(Foo):
    data +="def"

I am trying to change the attribute of the parent class in a subclass. I want my parent class to have some row, and my subclass should add extra data to this row. How should this be done in Python? Am I design wrong?

+4
source share
3 answers

You ask two questions:

  

How to do this in Python?

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

Am I design wrong?

  

I usually do not use class variables in Python. A more typical paradigm is the initialization of 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'
>>> 
+5
source

Foo Bar :

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

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

Bar, , :

abcdef
+3

You can reference variables of the Foo class from the Bar namespace through regular access to the attribute:

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

I do not know if this is good practice, but there is no reason for it to be bad.

+1
source

Source: https://habr.com/ru/post/1616404/


All Articles