Python调用类函数作为其他类的属性

问题描述 投票:0回答:2

是否可以创建这样的构造,其中类

foo
的类函数
A
是另一个类
B
的属性。那么这个函数应该在
A
的实例上调用,而不是直接调用
A.foo()

class A:
    def foo(self):
        print("Hallo")

class B:
    def __init__(self):
        self.func = A.foo
    
    def bar(self):
        obj = A()
        obj.self.func()

我的用例是,在

B
的构造函数中,可以选择
A
的不同函数作为
self.func
语句中的
if-else
属性,因此直接调用该函数是不可能的,因为不清楚是哪个函数将选择其中之一。

python function class attributes
2个回答
3
投票

在这种情况下,您可以显式传递实例:

class A:
    def foo(self):
        print("Hallo")

class B:
    def __init__(self):
        self.func = A.foo
    
    def bar(self):
        obj = A()
        self.func(obj)

0
投票

__init__()
方法中使用if else的解决方案:

class A:
    def foo(self):
        print("Hallo")

    def foo1(self):
        print("Hallo 1")

    def foo2(self):
        print("Hallo 2")

class B:
    def __init__(self, *x):
        if len(x) > 0:
            if x[0] == 1:
                self.func = A.foo1
            elif x[0] == 2:
                self.func = A.foo2
            else:
                self.func = A.foo
        else:
            self.func = A.foo

    def bar(self):
        self.func(A)

B().bar()
B(1).bar()
B(2).bar()

执行的输出为:

Hallo
Hallo 1
Hallo 2

输出显示

bar()
方法调用 A 类的不同方法,并且选择的方法取决于传递给
__init__()
方法的值(和存在)。

© www.soinside.com 2019 - 2024. All rights reserved.