【发布时间】:2015-08-03 20:54:28
【问题描述】:
总结
是否可以确定方法是通过属性调用而不是直接调用?
详情
我正在对一些代码进行一些 API 更改:旧 API 使用 Getters 和 Setters(GetAttr 和 SetAttr),而新的公共 API 将分别使用 x.Attr 和 x.Attr = val。我想在程序员调用GetAttr()时添加弃用警告
实际上,我正在寻找这个神奇的_was called_via_property 函数:
import warnings
class MyClass(object):
def __init__(self):
self._attr = None
def GetAttr(self):
if not _was_called_via_property():
warnings.warn("`GetAttr()` is deprecated. Use `x.attr` property instead.", DeprecationWarning)
return self._attr
def SetAttr(self, value):
if not _was_called_via_property():
warnings.warn("deprecated", DeprecationWarning)
self._attr = value
Attr = property(GetAttr, SetAttr)
理想情况下,如果除了 property() 函数之外还通过装饰器定义事物,该解决方案也可以工作,但这不是必需的。
像这样:
@property
def attr(self):
if not _was_called_via_property():
warnings.warn("deprecated", DeprecationWarning)
return self._attr
@attr.setter
def attr(self, value):
if not _was_called_via_property():
warnings.warn("deprecated", DeprecationWarning)
self._attr = value
【问题讨论】:
-
是的,我就是这么想的。呃,好吧。我有一个备用计划,我只是不想这样做,因为我很懒 :-P
标签: python python-3.x properties deprecation-warning