2014-09-26 15 views
0

我得到這個錯誤:
不受約束的方法你好()必須以實例作爲第一個參數來調用(什麼都沒有代替)在python中如何限制靜態方法?

import B 
class A(): 
    @staticmethod 
    def newHello(): 
     A.oldHello() # Here the error 
     print ' world' 

    def inject(self): 
     A.oldHello = B.hello 
     B.hello = A.newHello 


    A().inject() 
    B.hello() 

B.py只包含一個函數「你好」打印「你好」

def hello(): 
    print 'hello' 

在此先感謝

+0

你嘗試過B帶因爲它表明一個實例?你得到了什麼? – jollarvia 2014-09-26 16:05:04

+0

你的意思是叫oldHello(A())?該函數你好有1個參數,0需要 – user2054758 2014-09-26 18:06:52

回答

1

A.oldhello()也不是一成不變的。所以在B的hello函數中靜態引用A的nonstatic oldhello。 A確實需要一個實例。我對裝飾器不太熟悉,以及它們是如何工作的,但也許可以在函數之前在類中聲明oldhello並將其命名爲@staticmethod。如果您重寫該方法,我不知道靜態是否會繼續。

試試這個:

class B(): 
    def hello(self): 
     print "hello" 

class A(): 
    @staticmethod 
    def newHello(self): 
     A.oldHello(self) # Here the error 
     print ' world' 

    def inject(self): 
     A.oldHello = B.hello 
     B.hello = A.newHello 

A().inject() 
B().hello() 
+0

加入但同樣的錯誤:( – user2054758 2014-09-26 18:55:28