简体   繁体   English

使用 __getattr__() 调用 arguments 方法

[英]Calling method with arguments using __getattr__()

Recently, I saw the code below as an answer to a problem:最近,我看到下面的代码作为一个问题的答案:

class Proxy:
    def __init__(self, obj):
        self._obj = obj

    def __getattr__(self, attr):
        try:
            value = getattr(self._obj, attr)
        except Exception:
            raise Exception('No Such Method')
        else:
            return value

class Tmp:
    def __init__(self, num):
        self.num = num

    def set_num(self, num):
        self.num = num
        print(self.num)

tmp = Tmp(10)
tmp_proxy = Proxy(tmp)
tmp_proxy.set_num(12)

As you can see, it uses tmp_proxy to call set_num() method of object tmp .如您所见,它使用tmp_proxy调用 object tmpset_num()方法。 But I can't understand how it passes the argument num to this method, because as we print attr and its type, we see this:但我不明白它是如何将参数num传递给这个方法的,因为当我们打印attr及其类型时,我们会看到:

set_num
<class 'str'>

How does this work?这是如何运作的?

tmp_proxy doens't call set_num ; tmp_proxy调用set_num it provides a reference to the appropriate bound method.它提供了对适当绑定方法的引用。 value is that bound method, not the return value. value是绑定的方法,而不是返回值。 You could rewrite this code more explicitly:您可以更明确地重写此代码:

f = tmp_proxy.set_num  # get a bound method
f(12)  # call the bound method

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

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