2014-09-25 37 views
5

說我有一類與一羣方法:Python:爲類的任何方法做些什麼?

class Human(): 

    def eat(): 
    print("eating") 

    def sleep(): 
    print("sleeping") 

    def throne(): 
    print("on the throne") 

然後我跑所有

John=Human() 
John.eat() 
John.sleep() 
John.throne() 

我要爲被稱爲每種方法運行print("I am")方法。所以我應該得到像

I am: 
eating 
I am: 
sleeping 
I am: 
on the throne 

有沒有辦法做到這一點,而不必重新格式化每種方法?

+7

使用一個裝飾,它適用於所有方法:[將一個裝飾器附加到一個類中的所有函數](http://stackoverflow.com/q/3467526)和[編寫一個將裝飾器應用於所有方法的類裝飾器](http://stackoverflow.com/q/6695854) – 2014-09-25 11:33:52

+0

如果您想盡量減少需要編輯的編輯數量,最簡單的方法就是更改每個方法的定義。如果您正在尋找一種將變更隔離到單個地方的方法,以適用於當前或未來的任何方法,裝飾者就是要走的路。 – chepner 2014-09-25 12:09:29

+0

爲什麼不有一個函數'def do(self,action)',然後'eat'變成'self.do(「eating」)'並且輸出的任何進一步變化都發生在一個地方。 – jonrsharpe 2014-09-25 12:23:21

回答

5

如果你不能改變你怎麼稱呼你的方法,你可以使用__getattribute__魔術方法你(方法屬性也切記!)只是要注意檢查屬性的類型,所以你不打印「我:」您要訪問任何刺痛每一次或者int屬性,你可以有:

import types 

class Human(object): 
    def __getattribute__(self, attr): 
     method = object.__getattribute__(self, attr) 
     if not method: 
      raise Exception("Method %s not implemented" % attr) 
     if type(method) == types.MethodType: 
      print "I am:" 
     return method 

    def eat(self): 
     print "eating" 

    def sleep(self): 
     print "sleeping" 

    def throne(self): 
     print "on the throne" 

John = Human() 
John.eat() 
John.sleep() 
John.throne() 

輸出:

I am: 
eating 
I am: 
sleeping 
I am: 
on the throne 
-3

您可以編寫def iam()另一種方法和方法print "i am \n"編寫代碼和每個方法之前調用。

2

如果您不介意將__init____call__方法添加到您的課程,並且self用於您的方法參數,則可以這樣做。

class Human(): 
    def __init__(self): 
     return None 
    def __call__(self, act): 
     print "I am:" 
     method = getattr(self, act) 
     if not method: 
      raise Exception("Method %s not implemented" % method_name) 
     method() 

    def eat(self): 
     print "eating" 

    def sleep(self): 
     print "sleeping" 

    def throne(self): 
     print "on the throne" 

John = Human() 
John("eat") 
John("sleep") 
John("throne") 

編輯:看到我的其他答案一個更好的解決方案

+0

謝謝,但該解決方案改變了我如何調用的方法.. – Pithikos 2014-09-26 09:27:17

+0

@Pithikos看到我的其他答案,不需要你改變一個解決方案,你打電話給你的方法方式的語法 – nettux443 2014-09-26 12:55:15

相關問題