Python - is there a function that is called when the object does not implement the function?

In Smalltalk, a message DoesNotUnderstand appears, which is called when the object does not understand the message (this means that the object does not have a message sent).

So, I like to know if python has a function that does the same thing.

In this example:

 class MyObject: def __init__(self): print "MyObject created" anObject = MyObject() # prints: MyObject created anObject.DoSomething() # raise an Exception 

So, can I add a method to MyObject so that I can know when DoSomething supposed to be called?

PS: Sorry for my bad english.

+7
function python oop
source share
4 answers

Here is a suggestion on what you want to do:

 class callee: def __init__(self, name): self.name = name def __call__(self): print self.name, "has been called" class A: def __getattr__(self, attr): return callee(attr) a = A() a.DoSomething() >>> DoSomething has been called 
+7
source share

You are looking for the __getattr__ method. Take a look here .

If you want "full control" of a class, look at the special __getattribute__ method, then ( here ).

+3
source share

You have viewed the item. __getattr__(self, name) or object. __getattribute__(self, name) for new style classes? (see Special Method Names, Python Language Link )

+3
source share

I do not know why luc had two separate classes. You can do it all with one class if you use closure. For example:

 class A(object): __ignored_attributes__ = set(["__str__"]) def __getattr__(self, name): if __name__ in self.__ignored_attributes__: return None def fn(): print name, "has been called with self =", self return fn a = A() a.DoSomething() 

I added a bit about __ignored_attributes__ because Python was looking for __str__ in the class and figured it out a bit.

+2
source share

All Articles