简体   繁体   English

如何在Python类中顺序调用未定义的方法

[英]How to Call Undefined Methods Sequentially in Python Class

With getattr , I can do it like this : myclass.method1() 使用getattr ,我可以这样做: myclass.method1()

But I'm looking for something like myclass.method1().method2() or myclass.method1.method2() . 但是我正在寻找类似myclass.method1().method2()myclass.method1.method2()

It means that method1 , method2 are not defined in the class. 这意味着在类中未定义method1method2

Is there any way to call undefined methods sequentially in a Python class? 有什么方法可以在Python类中顺序调用未定义的方法吗?

I am not really sure, but it seems that what you are calling the undefined method is actually a normal method which you just want to call by name (because you obviously can not call something that is really not defined). 我不太确定,但是看来您所调用的undefined方法实际上是一个普通的方法,您只想按名称进行调用(因为您显然不能调用真正未定义的东西)。

In this case, you can nest getattr as many times as you need to go deeper, here is an example: 在这种情况下,您可以根据需要进行多次嵌套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'
)()

The last statement actually does another.method_another().method_test() . 最后一条语句实际上执行another.method_another().method_test()

This is what exactly that I've looked for: 这正是我一直在寻找的东西:

class MyClass:
    def __getattr__(self, name):
        setattr(self, name, self)
        def wrapper(*args, **kwargs):
            # calling required methods with args & kwargs
            return self
        return wrapper

Then I can call undefined methods sequentially like so: 然后,我可以依次调用未定义的方法,如下所示:

myclass = MyClass()
myclass.method1().method2().method3()

@Mortezaipo: You should set the attribute to the wrapper method, otherwise you can call the undefined methods only once: @Mortezaipo:您应该将属性设置为wrapper方法,否则只能调用一次未定义的方法:

class MyClass:
    def __getattr__(self, name):
        def wrapper(*args, **kwargs):
            # calling required methods with args & kwargs
            return self
        setattr(self, name, wrapper)
        return wrapper

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM