0

I have a problem with inheritance in Python.I have changed the member variable of ParentClass by itself.The problem is ChildClass cannot access to new value of ParentClass' member variable. Please look at this simple example:

class Parent(object):

    def __init__(self):

        self.name = "Tommy"

    def changeParentName(self):

        self.name = "Jack"


class Child(Parent):

    def parentName(self):

        print self.name    

parent = Parent()
parent.changeParentName()
child = Child()
child.parentName()

If you try above example, you'll see this result:

Tommy

But i expect to see Jack instead of Tommy. I have this problem with Python 2.7.9 Can anyone explain this problem or give us a solution? Does ChildClass call ParentClass' Constructor? so self.name equals Tommy again. Actually, i have this problem in my project, But i have explained my problem with above example

  • 2
    you need to read more about inheritance, classes and instances in general, your misunderstanding has nothing to do with python. – Ammar Mar 02 '15 at 18:16
  • I never blame python programming language. that's my misunderstanding. i should study more about OOP. – Amir M. Mir Mar 02 '15 at 18:45

1 Answers1

0

The two objects have nothing to do with each other.

>>> parent = Parent()
>>> parent.name
'Tommy'
>>> parent.changeParentName()
>>> parent.name
'Jack'

>>> child = Child()
>>> child.name
'Tommy'
>>> child.changeParentName()
>>> child.name
'Jack'

When you declare you class Child you are establishing inheritance.

class Child(Parent):

This means Child is a Parent. It does not mean that Parent has a Child.

See this similar question that discusses Inheritance vs Composition.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218