在 `__getattribute__` 的返回值上调用方法

call method on returned value of `__getattribute__`

我正在尝试以编程方式调用 class 属性的特定方法,Outer 调用下面 Inner 属性的 step 方法。我需要这样做,因为我将有可变数量的属性来实现步骤方法。

class Inner(object):
    def __init__(self):
        self.a = 0
    def step(self):
        self.a += 1

class Outer(object):
    def __init__(self):
        self.inner = Inner()
        self.step_attrs = []
        for attr in self.__dir__():
            if hasattr(self.__getattribute__(attr), 'step'):
                self.step_attrs.append(attr)
    def step(self):
        for attr in self.step_attrs:
            self.__getattribute__(attr).__getattribute__('step')()
        

outer = Outer()
print(outer.inner.a)
outer.step()
print(outer.inner.a)

此代码抛出:TypeError: expected 1 argument, got 0

如果我将 Outer().step 方法中的最后一行更改为

self.__getattribute__(attr).__getattribute__('step')(self.__getattribute__(attr))

失败 TypeError: step() takes 1 positional argument but 2 were given

如果我没看错,你需要这样的东西:

class Inner(object):
    def __init__(self):
        self.a = 0
    def step(self):
        self.a += 1

class Outer(object):
    def __init__(self):
        self.inner = Inner()
        self.step_attrs = [i for i in self.__dict__ if hasattr(self,"step")]
        print(self.step_attrs)

    def step(self):
        for j in self.step_attrs:
            getattr(self,j).step()

outer = Outer()
print(outer.inner.a)
outer.step()
print(outer.inner.a)

结果:

['inner']
0
1