Python:如何不遮蔽关键字'property'?

4 投票
2 回答
1152 浏览
提问于 2025-04-16 09:32

我正在维护一个老旧的Python应用程序,这个程序里有一个类是这样写的(还在用Python 2.4):

class MyClass(object):

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

现在我想在这个类里添加一些新代码:

    def _check_ok(self):
        ...

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

基本上,我想给这个类添加一个属性'ok'

但是它没有成功。我遇到了这个错误信息:

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

现有的类方法'property'覆盖了内置的'property'关键字。

有没有办法让我在新代码中像原本应该那样使用'property'

重构现有的property()函数不是一个选项。

编辑:如果我把新代码放在MyClass::property定义之前,它就能工作。但我真的想看看有没有更好的解决方案。

编辑 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: 'dict' object has no attribute 'property'的错误。

2 个回答

1

这样怎么样:

__builtins__.property(lamdba self:self._check_ok())
10

Python 2:

import __builtin__
__builtin__.property

Python 3:

import builtins
builtins.property

撰写回答