有了getattr,我可以这样做:myclass.method1()
但我正在寻找类似myclass.method1().method2()
或myclass.method1.method2()
的东西.
这意味着method1
,method2
不在类中定义。
有没有办法在 Python 类中按顺序调用未定义的方法?
我不太确定,但似乎你所说的未定义方法实际上是一个普通的方法,你只想按名称调用(因为你显然不能调用真正未定义的东西)。
在这种情况下,您可以根据需要嵌套getattr
多次以更深入,下面是一个例子:
class Test:
def method_test(self):
print('test')
class Another:
def __init__(self):
self._test = Test()
def method_another(self):
print('Another')
return self._test
another = Another()
getattr(
getattr(another, 'method_another')(),
'method_test'
)()
最后一句话实际上another.method_another().method_test()
.
这正是我所寻找的:
class MyClass:
def __getattr__(self, name):
setattr(self, name, self)
def wrapper(*args, **kwargs):
# calling required methods with args & kwargs
return self
return wrapper
然后我可以按顺序调用未定义的方法,如下所示:
myclass = MyClass()
myclass.method1().method2().method3()
@Mortezaipo:您应该将属性设置为包装器方法,否则只能调用一次未定义的方法:
class MyClass:
def __getattr__(self, name):
def wrapper(*args, **kwargs):
# calling required methods with args & kwargs
return self
setattr(self, name, wrapper)
return wrapper