Consider the following snippet in Python:
class A:
def f(self, arg):
print(self, arg)
class B(A):
@classmethod
def f(cls, arg):
super(B, cls).f(arg)
print(cls, arg)
B.f(1)
I know it's wrong to write like this, but I'm trying to understand what's going on behind the scenes. Why do I need to pass the first argument explicitly in call to inherited function? If this snippet is run, I get an exception that the required positional argument was not provided.
When I call Bf(1)
, the first argument (the class B
) is passed implicitly. I thought the same should be the case when I call the inherited ordinary method through class instance: self
should be class B
.
Is it some interpreter magic - say, it looks at class A
, sees that f
is ordinary function there, and does not set the first argument implicitly because it's called as class method?
I ran the code successfully by simply changing
super (B, cls).f(arg)
to:
super (B, cls).f (cls, arg)
and it worked fine. I guess the class isn't passed implicitly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.