As what I just learned, I can use super()
this way:super(class, obj_of_class-or-_subclass_of_class)
Code goes below:
#Case 1 class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() #ok, I can invoke A's __init__ successfully #Case 2 class A(object): @classmethod def foo(cls): print "A foo" class B(object): @classmethod def foo(cls): print "B foo" super(B, cls).foo() #ok, I can invoke A's foo successfully #Case 3 class A(object): def __new__(cls): print "A new" return super(A, cls).__new__(cls) class B(A): def __new__(cls): print "B new" return super(B, cls).__new__() #Oops, error
QUESTION:
In case 1 and 2, I can use super successfully without specifying the obj
or cls
to operate on. But why can't I do the same for __new__
? Because, in case 3, if I use super that way, I got an error. But if I use it this way:
super(B, cls).__new__(cls)
No error.
The __new__() is a static method of the object class. When you create a new object by calling the class, Python calls the __new__() method to create the object first and then calls the __init__() method to initialize the object's attributes.
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. Python super() The super() function allows us to avoid using the base class name explicitly.
From the Python release notes on overriding the __new__
method:
__new__
is a static method, not a class method. I initially thought it would have to be a class method, and that's why I added the classmethod primitive. Unfortunately, with class methods, upcalls don't work right in this case, so I had to make it a static method with an explicit class as its first argument.
Since __new__
is a static method, super(...).__new__
returns a static method. There is no binding of cls
to the first argument in this case. All arguments need to be supplied explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With