Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. 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:

set_num
<class 'str'>

How does this work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

tmp_proxy doens’t call set_num; it provides a reference to the appropriate bound method. value is that bound method, not the return value. You could rewrite this code more explicitly:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading