'super() and @staticmethod interaction
Is super() not meant to be used with staticmethods?
When I try something like
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
l = super(Second).getlist()
l.append('second')
return l
a = Second.getlist()
print a
I get the following error
Traceback (most recent call last):
File "asdf.py", line 13, in <module>
a = Second.getlist()
File "asdf.py", line 9, in getlist
l = super(Second).getlist()
AttributeError: 'super' object has no attribute 'getlist'
If I change the staticmethods to classmethods and pass the class instance to super(), things work fine. Am I calling super(type) incorrectly here or is there something I'm missing?
Solution 1:[1]
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.
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Y |
| Solution 2 | Peter |
