概括
是否可以确定是否通过属性调用方法而不是直接调用?
细节
我正在对一些代码进行一些 API 更改:旧 API 使用 Getters 和 Setters ( GetAttr
and SetAttr
),而新的公共 API 将分别使用x.Attr
and 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