python中嵌套类中的继承

2024-03-28 08:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道下面的示例中执行的是哪个类方法。有没有一种使用类名显式调用的方法?请帮忙

示例:-

class A():

    def test(self, input):
        print(input)


class B(A):
    def test(self, input):
        print(input)


class C(B):

    def testing(self):
        super().test("foo")
        super().test("boo")

run = C()
run.testing()

输出:-

foo
boo

为了进行实验,我尝试通过类名调用,但收到错误。我知道self是用于类对象的,因此应该通过super()或reference对象调用,但我的问题是,我如何知道在执行过程中调用的是哪个方法,是否有其他方法可以直接从类C显式调用父方法(从类A中调用)

class A():

    def test(self, input):
        print(input)


class B(A):
    def test(self, input):
        print(input)


class C(B):

    def testing(self):
        A.test("foo")
        B.test("boo")

run = C()
run.testing()

输出:-

 A.test("foo")
TypeError: test() missing 1 required positional argument: 'input'

Tags: 对象方法runtestself示例inputfoo
1条回答
网友
1楼 · 发布于 2024-03-28 08:26:52

有关@Samwise对错误消息给出的答案的其他信息:

方法是具有对象绑定的实际函数。当您在类的实例上调用函数时,python将用对该实例的引用填充函数的第一个参数,然后它将成为“方法”。但是,如果对类本身调用函数,python不会为您填充第一个参数,因此您必须自己完成。(这就是您得到的原因:missing 1 required positional argument: 'input'

class A:
    def foo(self):
        pass

print(type(A.foo))
print(type(A().foo))

正如你所看到的,第一个是“函数”,第二个是“方法”。在第一个例子中,您应该手动填写input(多么糟糕的名字)

这是描述符的行为。“函数”实现描述符协议

相关问题 更多 >