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.
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.