对“__getattribute__”的返回值调用方法
我试图以编程方式调用类属性上的特定方法,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 () 接受 1 个位置参数,但给出了 2 个
I'm trying to programmatically call a particular method on attributes of a class, Outer
calling the step
method on the Inner
attribute below. I need to do this because I'll have a variable number of attributes that implement the step method.
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)
This code throws: TypeError: expected 1 argument, got 0
If I changed the last line in the Outer().step
method to
self.__getattribute__(attr).__getattribute__('step')(self.__getattribute__(attr))
it fails with TypeError: step() takes 1 positional argument but 2 were given
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我没猜错的话,你需要这样的东西:
结果:
if i got you right, you need somethig like this :
Result :