Here is 2 classes:

class Test(object):
    def __init__(self, var1=123):
        self.var1 = var1

class Test2(Test):
    # ...

As you can see, Test2 is an instance of Test, which has var1. var1's default value is 123.

How can I change the var1 in Test2 without __init__ again? Or better yet, can I just do this (I know it doesn't work, but is there a way to make this work?):

class Test2(Test):
    var1 = 1234

Secondly, how can I modify __init__ in Test2 without replacing all the code that's written in Test1?

Recommended Answers

All 4 Replies

Simple example of inheritance in python.

class Basic:
    def __init__(self):
        self.var1 = None

#This class inherits all aspects from Basic and can change them
class Test(Basic):
    def __init__(self):
        Basic.__init__(self)

def main():
    testClass = Test()
    testClass.var1 = 5
    print testClass.var1

if __name__ == '__main__':
    main()

One way to look at this problem:

class Test(object):
    def __init__(self, var1=123):
        self.var1 = var1

    def show(self):
        print(self.var1)


class Test2(Test):
    # create self
    def __init__(self):
        # make inherited class Test part of self
        Test.__init__(self)
        self.show()  # 123
        self.var1 = 777
        self.show()  # 777


t2 = Test2()

so this would add to the original __init__?

class Test(object):
    def __init__(self,var1=123):
        self.var1 = var1

class Test2(Test):
    def __init__(self, var2=1234):
        Test.__init__(self) #Here's where I'm not sure
        self.var2 = var2

t2 = Test2()

# Now would t2 have both var1 and var2?

Let's test it:

class Test(object):
    def __init__(self,var1=123):
        self.var1 = var1

class Test2(Test):
    def __init__(self, var2=1234):
        Test.__init__(self)
        self.var2 = var2
        # test it ...
        print(self.var1, self.var2)  # 123 1234

t2 = Test2()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.