2009-11-30 70 views
7

在Smalltalk中,有一条消息DoesNotUnderstand,当对象不理解消息时(也就是说,当对象没有实现消息时)会调用该消息。Python - 存在一个函数,当对象没有实现一个函数时被调用?

所以,我想知道是否在Python中有一个功能,做同样的事情。

在这个例子中:

class MyObject: 
    def __init__(self): 
     print "MyObject created" 

anObject = MyObject() # prints: MyObject created 
anObject.DoSomething() # raise an Exception 

所以,我可以添加到MyObject的方法,所以我可以知道什么时候DoSomething被intented被称为? PS:对不起,我的英语不好。

回答

7

这里是一个命题,你想做什么:

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 
+0

这绝对是我想要的!谢谢:) – 2009-11-30 14:48:57

+0

我喜欢它,当有人绝对是挑衅! (或者是“definntly确定”?)​​无论如何,SO再次拯救了这一天! :) – PaulMcG 2009-11-30 23:12:18

3

您正在寻找__getattr__方法。看看here

如果你想要一个班级的“总控制”,那么看看__getattribute__特殊的方法然后(here)。

2

我不知道为什么LUC有两个独立的类。如果你使用闭包,你可以用一个类来完成。像这样:

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() 

我加了一些关于__ignored_attributes__因为Python一直在寻找在类的__str__,并且得到了一个有些凌乱。

+1

两个类,因为它可以更容易地重用。想象一下你对B类想要相同的行为 – luc 2010-05-07 04:40:32

相关问题