Python Forum

Full Version: Help with Classes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have this code:
class Parent:
    def __init__(self):
        self.name = "Parent"

    def create_child(self):
        x = Child()

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
        print(self.name)

x = Parent()
x.name = "Parent2"
x.create_child()
print(x.name)
Which Outputs:
Output:
Parent Parent2
It is creating a new instance of Parent when Child is called.
I don't want this. Is there a way of accessing parent variables and methods without using object.__init__(self,*args,**kwargs)?
Thanks!
It's not creating a new instance of Parent, it is creating a new instance of Child. That new instance of Child calls Parent.__init__, which names the child 'Parent'. Then Child.__init__ prints that name. Then the last line prints the name of the Parent class you created, which you had renamed 'Parent2' on line 14. Note that the x in create_child is not the same as the global x used on lines 13-16. That instance of the child class is discarded when create_child finishes processing.

(Jul-09-2018, 12:22 PM)sam57719 Wrote: [ -> ]I don't want this. Is there a way of accessing parent variables and methods without using object.__init__(self,*args,**kwargs)?

What do you mean by 'accessing'? If you mean calling, you can use super(Child, self).__init__(). But it's going to have the same effect. Part of the problem here is that it's not clear what effect you want. If you could clarify exactly what you are expecting, it would help us solve the problem.