views:

110

answers:

2

Hello,

I am trying to get completely to grips with class inheritence in Python. I have created program's with classes but they are all in one file. I have also created scripts with multiple files containing just functions. I have started using class inheritence in scripts with multiple files and I am hitting problems. I have 2 basic scripts below and I am trying to get the second script to inherit values from the first script. The code is as follow's:

First Script:

class test():

    def q():

        a = 20
        return a

    def w():
        b = 30
        return b

    if __name__ == '__main__':
        a = q()
        b = w()

if __name__ == '__main__':
    (a, b) = test()

Second Script:

from class1 import test

class test2(test):

    def e(a, b):
        print a
        print b


    e(a, b)

if __name__ == '__main__':
    test2(test)

Can anyone explain to me how to get the second file to inherit the first files values? Thanks for any help.

+9  A: 

I would say you messed up class definition with function stuff. It should look more like this:

class Test(object):

    def __init__(self):
        self.a = 20
        self.b = 30

if __name__ == '__main__':
    test_instance = Test()

and

from class1 import Test

class Test2(Test):

    def e(self):
        print self.a
        print self.b


if __name__ == '__main__':
    test_instance = Test2()
    test_instance.e() # prints 20 and 30

It looks like your problem is not (only) inheritance, but also how to correctly define classes in Python.

Some notes:

  • Always use capitalized names for classes. That is more or less convention.
  • As ruibm pointed out, every (non-static) method of a class has to have a first parameter that is named (by convention) self.
  • You can create instance variables by setting them as self.variable = value in the __init__ method.
  • If you call Test() you get an object back. Unless you assign it to a variable, just calling test2() as you did in your second piece of code has no effect. Maybe it had in your case because defined your class in a weird way.
Felix Kling
Much better than my answer. I shouldn't have been lazy to the point of not writing code! Well done. :)
ruibm
+1  A: 

In Python, each member function (method) of a class should have a variable called self which is pretty much the this pointer/reference in C++, Java, C#.

Basically, to make your code work add self as the first argument to all methods. To assign/read member variables use self.a and self.b otherwise you're just creating temporary function variables the way you have it right now.

ruibm