Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__getattr__ equivalent for methods

When an attribute is not found object.__getattr__ is called. Is there an equivalent way to intercept undefined methods?

like image 773
hoju Avatar asked Oct 04 '10 12:10

hoju


People also ask

Does Getattr work with methods?

Okay, so it's cool that you can use getattr to get methods as well as propertiespropertiesA property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method.https://en.wikipedia.org › wiki › Property_(programming)Property (programming) - Wikipedia, but how does that help us? Well, this can definitely be useful in keeping your code DRY if you have some common logic surrounding branching method calls.

What does __ Getattr __ do in Python?

Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned.

What is Getattr () used for l1?

Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key. Parameters : obj : The object whose attributes need to be processed. key : The attribute of object.

What is the difference between Getattr and Getattribute?

__getattribute__ has a default implementation, but __getattr__ does not. This has a clear meaning: since __getattribute__ has a default implementation, while __getattr__ not, clearly python encourages users to implement __getattr__ .


2 Answers

There is no difference. A method is also an attribute. (If you want the method to have an implicit "self" argument, though, you'll have to do some more work to "bind" the method).

like image 183
Arafangion Avatar answered Sep 19 '22 12:09

Arafangion


Methods are attributes too. __getattr__ works the same for them:

class A(object):

  def __getattr__(self, attr):
    print attr

Then try:

>>> a = A()
>>> a.thing
thing
>>> a.thing()
thing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
like image 29
detly Avatar answered Sep 21 '22 12:09

detly