super() and @staticmethod interaction
The short answer to
Am I calling super(type) incorrectly here or is there something I'm missing?
is: yes, you're calling it incorrectly... AND (indeed, because) there is something you're missing.
But don't feel bad; this is an extremely difficult subject.
The documentation notes that
If the second argument is omitted, the super object returned is unbound.
The use case for unbound super
objects is extremely narrow and rare. See these articles by Michele Simionato for his discussion on super()
:
- Things to Know About Python Super [1 of 3]
- Things to Know About Python Super [2 of 3] (this one specifically covers unbound super)
- Things to Know About Python Super [3 of 3]
Also, he argues strongly for removing unbound super
from Python 3 here.
I said you were calling it "incorrectly" (though correctness is largely meaningless without context, and a toy example doesn't give much context). Because unbound super
is so rare, and possibly just flat-out unjustified, as argued by Simionato, the "correct" way to use super()
is to provide the second argument.
In your case, the simplest way to make your example work is
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
l = super(Second, Second).getlist() # note the 2nd argument
l.append('second')
return l
a = Second.getlist()
print a
If you think it looks funny that way, you're not wrong. But I think what most people are expecting when they see super(X)
(or hoping for when they try it in their own code) is what Python gives you if you do super(X, X)
.
Since Second inherits form First, you can just use First.getlist()
instead of passing in two arguments in super(i.e. super(Second, Second)
)
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
# l = super(Second, Second).getlist()
l = First.getlist()
l.append('second')
return l
a = Second.getlist()
print (a)
When you call a normal method on a object instance, the method receives the object instance as first parameter. It can get the class of the object and its parent class, so it makes sense to call super
.
When you call a class method on an object instance or on a class, the method receives the class as first parameter. It can get the parent class, so it makes sense to call super
.
But when you call a static method, the method does not receive anything and has no way to know from what object or class it was called. That's the reason why you cannot access super
in a static method.