简体   繁体   中英

Altering parent variable through child class function in Python

so I just recently started doing OOP in python and I do not have a lot of knowledge in OOP in general. I was wondering if I am able to create Child classes through a parent class and then alter the Parent class variable through the Child class created?

class Parent:
    def __init__(self, var1, var2, var3):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3

    def create_child(self, count):
        array = []
        for x in range(count):
            array.append(Child(var4=self.var1))
        return array

class Child(Parent):
    def __init__(self, var4):
        super(Parent, self).__init__()
        self.var4 = var4

    def alter_parent_variable(self, value):
        self.var1 += value

Say I've created a code as seen above I keep getting an error saying:

TypeError: init () missing 3 required positional arguments: 'var1', 'var2', and 'var3'

By using this code to test:

test = Parent(20, 50, 1)

array = test.create_child(3)

for x in array:
    x.alter_parent_variable(50)

And lets say I added another function with the exact same code as seen in the Parent class into the Child class (As listed below). Am I able to directly alter the Parent class variable through the Child class created by the Child class?

    def create_child(self, count):
    array = []
    for x in range(count):
        array.append(Child(var4=self.var1))
    return array

You're getting TypeError because you're calling Parent 's __init__ (when you call super(Parent, self).__init__() ) without giving enough args.

The way you are modifying Parent 's var1 won't work, because while Child inherits from Parent , they won't be the same class instance ( self always refers to the class instance , not the class itself).

But, you can pass a reference to Parent itself by passing self , and modify var1 that way.

For example:

class Child(Parent):
    def __init__(self, var4, parent: Parent):
        self.var4 = var4
        self.parent = parent

    def alter_parent_variable(self, value):
        self.parent.var1 += value

That said, depending on what you're ultimately trying to achieve, there may be better ways of doing things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM