Home > OS >  what arg can I use instead of `*args` in child (multiple-inheritance) instance?
what arg can I use instead of `*args` in child (multiple-inheritance) instance?

Time:01-05

what arg can I use instead of *args in the child instance? For example in this code:

class Foo:
    class_var = 'bar'
    def __init__(self):
        self.instance_var = 'baz'

class Test(Foo):
    def __init__(self, instance_var):
        Foo.__init__(self)
        self.new_instance = "duck"

child1 = Test(Foo) 
print("child1.instance_var: ", child1.instance_var)

The output is:

child1.instance_var:  baz

..but when I create the next child, the script works only when I change def __init__(self, instance_var): to def __init__(self, *args):. Without that I get "TypeError: init() missing 1 required positional argument: 'instance_var'".

This code works:

class Foo:
    class_var = 'bar'
    def __init__(self):
        self.instance_var = 'baz'

class Test(Foo):
    def __init__(self, *args):
        Foo.__init__(self)
        self.new_instance = "duck"

child1 = Test(Foo) 
print("child1.instance_var: ", child1.instance_var)

class Test1(Test):
    def __init__(self, *args):
        Test.__init__(self)
        self.new_instance = "new_duck"

child2 = Test1(Test)        
print("child2.instance_var: ", child2.new_instance)

The output is:

child1.instance_var:  baz
child2.instance_var:  new_duck

But, this one doesn't:

class Foo:
    class_var = 'bar'
    def __init__(self):
        self.instance_var = 'baz'

class Test(Foo):
    def __init__(self, instance_var):
        Foo.__init__(self)
        self.new_instance = "duck"

child1 = Test(Foo) 
print("child1.instance_var: ", child1.instance_var)

class Test1(Test):
    def __init__(self, *args):
        Test.__init__(self)
        self.new_instance = "new_duck"

child2 = Test1(Test)        
print("child2.instance_var: ", child2.new_instance)

I don't understand fully why (where should I place instance_var so the code won't throw an error). What's the logic: step by step?

CodePudding user response:

The problem was that I tried to declare instance_var in

class Test(Foo):
    def __init__(self, instance_var):

The code works with just self, or with self, *args in a child class.

class Foo:
    class_var = 'bar'
    def __init__(self):
        self.instance_var = 'baz'

class Test(Foo):
    def __init__(self):
        Foo.__init__(self)
        self.new_instance = "duck"

child1 = Test() 
print("child1.instance_var: ", child1.instance_var)

class Test1(Test):
    def __init__(self):
        Test.__init__(self)
        self.new_instance = "new_duck"

child2 = Test1()        
print("child2.instance_var: ", child2.new_instance)

That solves the problem with "TypeError: init() missing 1 required positional argument: 'instance_var'" when *args is moved.

  •  Tags:  
  • Related