2

I'm having problem using super command

class s:
    def __init__(self,a):
        self.a=a

    def show(self):
        print self.a


class t:
    def __init__(self,b):
        self.b=b

    def show2(self):
        print self.b


class w(s):
    def __init__(self,a,b,c):
        super(w,self).__init__()
        self.b=b
        self.c=c

    def show3(self):
        super(w,self).show()
        print self.b
        print self.c

whenever i make an object it gives the following error

x=w(1,2,3)

Traceback (most recent call last):
    File "<pyshell#0>", line 1, in <module>
x=w(1,2,3)
File "C:\Users\GURSAHEJ\Desktop\k.py", line 13, in __init__
super(w,self).__init__()
TypeError: must be type, not classobj
Tim
  • 41,901
  • 18
  • 127
  • 145

2 Answers2

1

The super function will Return a proxy object that delegates method calls to a parent or sibling class of type so when you want to use it you need to pass the parent name to it,and since here your w class inherit from s you might want to pass s to super:

class w(s):
    def __init__(self,a,b,c):
        super(s,self).__init__()
        self.b=b
        self.c=c

Also don't forget to pass the object to your parent class to make it a new style class :

class s(object):
        def __init__(self,a):
            self.a=a
        def show(self):
            print self.a

Read about new style and classic classes it in python documentation https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes

Community
  • 1
  • 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Because you are using super on an old-style class

In Python 2.x (>= 2.2), there are two type of classes. Old style classes and new-style classes. In python 3.x, old-style classes are removed and all classes are new-style class.

Python's build-in function super works properly on new-style classes.

Simply, new-style classes extends object while old style classes not.

Old Sytle Class

class s:
    def __init__(self,a):
        self.a=a

New Style Class

class s(object):
    def __init__(self,a):
        self.a=a

So, your classes which is not inherited from another class should be inherited from object to be a new style class.

You can either use new-style or use old-skool inheritance __init__

class w(s):
    def __init__(self,a,b,c):
        s.__init__(self, a)

This is an example of old-style solution, but I do not flag this question as a duplicate because new-style class usage is encouraged and you should avoid using old-style classes.

Community
  • 1
  • 1
Mp0int
  • 18,172
  • 15
  • 83
  • 114