2011-01-07 50 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