6

i have a code like this:

class sampleClass(object):
    def __init__(self):
        super(sampleClass, self).__init__()

my question is that why it calls super of itself under __init__ ?

i know that super is used for calling the parent class's __init__, (if I'm wrong tell me) , but here what does it do ?

anon
  • 433
  • 1
  • 8
  • 14

2 Answers2

3

It doesn't call the __init__ of it's self that's the correct syntax of super which the first argument must be the class itself (the class name that super will call its parent's __init__).

Read more here https://docs.python.org/3.6/library/functions.html#super

super([type[, object-or-type]])

Return a proxy object that delegates method calls to a parent or sibling class of type. [the first argument]

Community
  • 1
  • 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188
-2

As far as I understand, this type of class definition enables to differentiate new type classes from old type classes in Python 2. However, Python 3 is using only new type classes by definition. Therefore, this kind of implementation is not necessary if you are using Python 3 but it helps for back compatibility.

https://www.reddit.com/r/learnpython/comments/7vou1s/what_does_object_in_class_classnameobject_do/dttx467/?utm_source=reddit&utm_medium=web2x&context=3

This link contains more information regarding differences of class definitions in Python 2 and Python 3.

Basically, you can turn your class definition into this if you are using Python 3.

class sampleClass():
    def __init__(self):
        ...
    
Bahad
  • 27
  • 3
  • This definition of ``sampleClass`` is *not* equivalent to what is shown in the question. It will behave differently when used with multiple inheritance, failing to call its superclass. – MisterMiyagi Feb 16 '21 at 11:57
  • Please check again and read carefully. It is exactly the same for Python. I even changed couple code of mine from the first type of definition to my type of definition and it works! As you can see, in the question, `sampleClass` inherits `object`. jsbueno explained what object is in here [link](https://stackoverflow.com/questions/10043963/class-classname-versus-class-classnameobject) . Therefore, there is no superclass that needs to be inherited in the question like you mentioned. – Bahad Feb 16 '21 at 13:04
  • Again, in the case of multiple inheritance, say ``class C(sampleClass, dict):``, there *is* a superclass different from object. Superclasses are not static, that's the entire point of having ``super`` instead of calling the superclass by name. – MisterMiyagi Feb 16 '21 at 14:13
  • See for example [Raymond Hettinger's blog on multiple inheritance](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/) for an explanation how the superclass can change via multiple inheritance. – MisterMiyagi Feb 16 '21 at 14:20