1

I have trouble understanding the logic of instance variables in inheritance. This is my (simplified) code with comments explaining how I understand its behaviour:

class Main(object):

    def __init__(self):
        self.p = Parent()  # self.parameter = []
        self.c = Child()  # self.parameter = []

    def run(self):
        self.p.setting()  # assigning value to self.parameter
        self.c.getting()


class Parent(object):

    def __init__(self):
        self.parameter = []

    def setting(self):
        self.parameter = [1, 2, 3]


class Child(Parent):
    # not redefining __init__, so Parent __init__ is called

    def getting(self):
        # value was assigned to self.parameter in setting method,
        # called before getting
        print self.parameter


Main().run()

getting prints [], instead of [1, 2, 3] which I expected. Why is it so? Since Child shares __init__ with Parent, at the beginning self.parameter = [] for both but why is it still [] when it was assigned a value long after Child().__init__ was called? What should I do to get changed self.parameter value in getting?

1
  • Python is not Java; not everything has to be a class. Get rid of Main. Commented Oct 10, 2017 at 13:53

2 Answers 2

2

Let's go through execution of your code.

  1. main instance is created with Main().

At this moment we have main.p = [] and main.s = [], as defined in Main.__init__

  1. main.run() is called, and it calls main.p.setting() and main.c.getting()

So now, main.p.setting() changes the parameter value of main.p to [1,2,3], and main.c.setting() just prints its own parameter value, which is still [], as it was never modified.

If you want to modify main.c.parameter value, simply call main.c.setting()

main = Main()
main.c.setting()
main.run()
Sign up to request clarification or add additional context in comments.

Comments

2

You're not inheriting from anything here in Main, you're adding member variables. You're expressing a "has a" relationship, not an "is a".

To inherit, define Main as such:

class Main(Child):

    def run(self):
        self.setting()
        self.getting()

With your current code, you could inspect main_instance.p.parameter after calling main_instance.run() and see that [1, 2, 3] is returned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.