[PYTHON] A story exhausted by super (A, self)

What i want to say

It is better to write super () instead of super (A, self).

Background

For some reason, you must declare a class named A more than once in the same module. Roughly, this kind of code is written.

fool1.py


class A:
    pass

a11 = A()
a12 = A()


class A:
    pass

a21 = A()
a22 = A()

A class definition is, in other words, the creation of a class object (by type), so the two A classes are separate objects. Naturally, it will be like this.

>>> a11.__class__ is a12.__class__
True
>>> a21.__class__ is a22.__class__
True
>>> a11.__class__ is a21.__class__
False
>>> a12.__class__ is a22.__class__
False

I was troubled by using super (A, self) to make unexpected movements without being aware of this. For example, consider the following definition.

class Asuper:
    pass


class A(Asuper):
    def get_super1(self):
        return super(A, self)

    def get_super2(self):
        return super()

    def get_super3(self):
        return super(self.__class__, self)

If you instantiate A and call get_super [123], you get:

>>> a = A()
>>> a.get_super1()
<super: <class 'A'>, <A object>>
>>> a.get_super2()
<super: <class 'A'>, <A object>>
>>> a.get_super3()
<super: <class 'A'>, <A object>>

Then, after instantiating A once, redefine A and try the same.

>>> a = A()
>>> class A:
...     pass
... 
>>> a.get_super1()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in get_super1
TypeError: super(type, obj): obj must be an instance or subtype of type
>>> a.get_super2()
<super: <class 'A'>, <A object>>
>>> a.get_super3()
<super: <class 'A'>, <A object>>

Only get_super1 using super (A, self) has a TypeError. The constraint violation was probably caused by the switching of the object referenced by the name ʻAin the running module. To avoid this, it's a good idea to specify a class object that the object references, such as get_super3. It is unconfirmed, but I think that if you omit the argument ofsuper`, it will behave like this.

Recommended Posts

A story exhausted by super (A, self)
A story about data analysis by machine learning
A story about making a tanka by chance with Sudachi Py
A story about a tragedy happening by exchanging commands in chat
A super introduction to Linux
What is a super user?