-1

I have below code:

class Parent():
    def __init__(self,name):
       self.name = name
    def printing(self):
       print(self.name)

class Child (Parent):
    def __init__(self,name,country):
       Parent.name = 'Roger'
       self.name = name
       self.country = country
    def Output(self):
       print(Parent.name,self.name,self.country)

obj = Child('Rafael','France')

Now, obj.Output() returns: Roger Rafael France

and obj.printname() returns: Rafael

Can anybody please explain why assigning Parent.name = 'Roger' didn't change it in the parent class? Want to understand why `Parent.name' is not getting overridden.

Sunder
  • 85
  • 1
  • 9
  • Possible duplicate of [python subclass access to class variable of parent](https://stackoverflow.com/questions/3648564/python-subclass-access-to-class-variable-of-parent) – Spinor8 Nov 10 '17 at 15:24
  • 1
    I think you are mixing class attributes with object attributes – lpozo Nov 10 '17 at 15:27
  • right and anyway in this case it doesn't make much sense to have `Child` inherit from `Parent` because you are going to be overriding `Parent` attributes and `obj.name` can only refer to a single value – avigil Nov 10 '17 at 15:34

2 Answers2

1

because obj = Child('Rafael','France') is an instance of class Child and in lines:

   Parent.name = 'Roger'
   self.name = name

you override Roger's name with a name of an instance self.name = name which you are setting in constructor.

To work the way you want, code should look like:

class Parent():
    def __init__(self,name):
       self.name = name

    def printing(self):
       print(self.name)

class Child (Parent):
    def __init__(self,name,country):
       self.name = name
       Parent.name = 'Roger' # but this is awful
       self.country = country

obj = Child('Rafael','France')
obj.printing()
> Roger
py_dude
  • 822
  • 5
  • 13
  • `self.name` refers to the same attribute in `Parent` and `Child` classes. I don't think its possible to modify one without the other. – avigil Nov 10 '17 at 15:30
  • right but `super().__init__(name='Roger')` will also change `self.name` so that `obj.name` will always be `Roger`! – avigil Nov 10 '17 at 15:36
  • @ArthurVigil agreed – py_dude Nov 10 '17 at 16:01
  • The above code in my Jupyter notebook still results in output 'Rafael'. However, understood your point - `self.name=name` is overriding the `Parent.name = Roger`. Removing `self.name=name` in the Child `__init__` is resulting in output 'Roger'. I think the order of the statements is not making any difference. – Sunder Nov 10 '17 at 17:54
1

You hid the reference to Parent's self.name when you created your own self.name in Child's init.

What you want to do is call Parent's constructor: How to invoke the super constructor?

And then, access it like this: Access parent class instance attribute from child class instance?

Pablo Oliva
  • 334
  • 3
  • 12