2011-01-07 49 views
3

我支持它有像這樣寫的(在Python 2.4仍然運行)一類遺留 Python應用程序:Python:如何淡化關鍵字「屬性」?

class MyClass(object): 

    def property(self, property_code, default): 
     ... 

現在我加入了一些新的代碼吧:

def _check_ok(self): 
     ... 

    ok = property(lamdba self:self._check_ok()) 

基本上我想添加一個屬性'好'到這個類。

但它不起作用。我遇到了這個錯誤信息:

TypeError: property() takes at least 2 arguments (1 given) 

現有的類方法'屬性'已經掩蓋了內置的'屬性'關鍵字。

有沒有什麼辦法可以使用'property'它的意思是在我的新代碼中?

重構現有的property()函數不是一個選項。

編輯:如果我把新代碼放在MyClass::property def之前,它就會工作。但我真的想看看有沒有更好的解決辦法

編輯2:這些代碼在外殼

>>> class Jack(object): 
... def property(self, a, b, c): 
...  return 2 
... p = __builtins__.property(lambda self: 1) 
... 
>>> a = Jack() 
>>> a.p 
1 
>>> a.property(1, 2, 3) 
2 

工作,但相同的技術並不在我的應用程序工作。得到AttributeError的: '快譯通' 對象有沒有屬性 '財產'錯誤

+0

您使用了__builtins__,當您使用__builtin__時,會發生什麼情況,如Thomas K所建議的? – 2011-01-07 01:40:31

+0

難道你不能只有`ok = property(_check_ok)`?或者使用裝飾器(`_check_ok` def上方的@屬性)?根據您的解決方案,當然您可能需要更全面地限定「財產」。 – detly 2011-01-07 01:42:44

回答

8

的Python 2:

import __builtin__ 
__builtin__.property 

的Python 3:

import builtins 
builtins.property 
0

如何:

__builtins__.property(lamdba self:self._check_ok()) 
+0

獲取此錯誤:AttributeError:'詞典'對象沒有屬性'屬性'。但如果我嘗試了你的殼,它的工作原理。 – 2011-01-07 01:35:46