【问题标题】:Python: How to unshadow the keyword 'property'?Python:如何消除关键字“属性”的阴影?
【发布时间】:2011-06-05 00:52:50
【问题描述】:

我支持一个 legacy 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 def 之前,它将起作用。但是我很想看看有没有更好的解决方案

编辑 2:这些代码在 shell 中工作

>>> 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' 错误

【问题讨论】:

  • 您使用了 builtin,当您按照 Thomas K 的建议使用 builtin 时会发生什么?
  • 你不能只有ok = property(_check_ok)吗?还是使用装饰器(_check_ok def 上方的@property)?当然,根据您的解决方案,您可能必须更全面地限定property

标签: python


【解决方案1】:

这个怎么样:

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

【讨论】:

  • 得到这个错误:AttributeError: 'dict' object has no attribute 'property'。但是,如果我在 shell 中尝试了你的,它就可以工作。
  • 对不起 - 我在提示符下进行了测试。在脚本中,您“导入 builtin”并像 Thomas K 所说的那样执行 builtin.property。
【解决方案2】:

Python 2:

import __builtin__
__builtin__.property

Python 3:

import builtins
builtins.property

【讨论】:

  • 谢谢托马斯,它有效。只是不明白为什么 __builtins__.property 在 shell 中工作......
  • 短版:它是 Python 的一个混乱部分,因为 __builtins__ 可以是字典或模块。见stackoverflow.com/questions/1184016/…stackoverflow.com/questions/2173425/…
  • 如果它与任何人相关:在 Python 3 中,您使用 import builtins(复数,没有下划线),而不是 import __builtin__
猜你喜欢
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 2012-09-21
  • 1970-01-01
  • 2015-08-30
相关资源
最近更新 更多