Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Exists a function that is called when an object does not implement a function?

In Smalltalk there is a message DoesNotUnderstand that is called when an object does not understand a message (this is, when the object does not have the message sent implemented).

So, I like to know if in python there is 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 I can know when DoSomething is intented to be called?

PS: Sorry for my poor English.

like image 607
Lucas Gabriel Sánchez Avatar asked Nov 30 '09 14:11

Lucas Gabriel Sánchez


People also ask

How do you check if an object is a function in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

What is the type of a function object in Python?

Functions in python are first class objects. This means that they can be passed as arguments to other functions, assigned to variables or even stored as elements in various data structures.


1 Answers

Here is a proposition for 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
like image 68
luc Avatar answered Sep 19 '22 21:09

luc