简体   繁体   English

子类方法在Python中调用父类的普通方法

[英]Child class method calling parent class ordinary method in Python

Consider the following snippet in Python: 请考虑以下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. 当我调用Bf(1) ,第一个参数(类B )被隐式传递。 I thought the same should be the case when I call the inherited ordinary method through class instance: self should be class B . 我认为通过类实例调用继承的普通方法时也应如此: self应该是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? 这是某种解释魔术吗?例如,它查看类A ,看到f是那里的普通函数,并且因为被称为类方法而没有隐式设置第一个参数?

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. 我猜该类不是隐式传递的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM