1

I'm trying to print method's name using __getattribute__

but I get typeerror everytime I called the method, and the method is not excuted, is there anyway to get rid of the type error and have the method excuted ?

class Person(object):
    def __init__(self):
        super()

    def test(self):
        print(1)

    def __getattribute__(self, attr):
        print(attr)



p = Person()

p.test()

The above code gives the error

test
Traceback (most recent call last):
  File "test1.py", line 15, in <module>
    p.test()
TypeError: 'NoneType' object is not callable

Is there anyway to print the method's name only without giving the error ?

I tried to catch typeError inside __getattribute__ method, but it doesn't work

Another question is, why it says None Type object is not callable here

Thank you !

Ps. I know I can catch the error when I call the method, I mean is there anyway to deal this error inside __getattribute method? since my goal is to print method's name everytime a method is called

1 Answer 1

1

Answering your second question first, why is it saying NoneType not callable.

When you call p.test() Python tries to lookup the test attribute of the p instance. It calls the __getattribute__ method that you've overridden which prints 'test' and then returns. Because you're not returning anything it implicitly returns None. p.test is therefore None and calling it gives the error you get.

So how do we fix this? Once you've printed the attribute name, you need to return the attribute you're after. You can't just call getattr(self, attr) or you'll end up in an infinite loop so you have to call the method that would have been called if you hadn't overridden it.

def __getattribute__(self, attr):
    print(attr)
    return super().__getattribute__(attr) # calls the original method
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ! very clear explanation, and the code works !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.