2009-11-30 68 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

相關問題