1

概括

是否可以确定是否通过属性调用方法而不是直接调用?

细节

我正在对一些代码进行一些 API 更改:旧 API 使用 Getters 和 Setters ( GetAttrand SetAttr),而新的公共 API 将分别使用x.Attrand 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
4

2 回答 2

2

您无法区分property描述符访问和直接访问,不。

创建一个适当的属性,并为其使用旧方法代理:

@property
def attr(self):
    return self._attr

@property.setter
def attr(self, value):
    self._attr = value

# legacy access to the attr property
def GetAttr(self):
   warnings.warn("deprecated", DeprecationWarning)
   return self.attr

def SetAttr(self, value):
   warnings.warn("deprecated", DeprecationWarning)
   self.attr = value
于 2015-08-03T21:03:49.880 回答
1

另一种解决方案是包装property

def myprop(getter, setter):
    return property(lambda self : getter(self, True), 
                    lambda self, x : setter(self, x, True))


class MyClass(object):
    def __init__(self):
        self._attr = None

    def GetAttr(self, called_via_property=False):
        if not called_via_property:
            warnings.warn("`GetAttr()` is deprecated. Use `x.attr` property instead.", DeprecationWarning)
        return self._attr

    def SetAttr(self, value, called_via_property=False):
        if not called_via_property:
            warnings.warn("deprecated", DeprecationWarning)
        self._attr = value

    Attr = myprop(GetAttr, SetAttr)

另一种解决方案可能是覆盖__getattr____setattr__生成带有警告的 g​​etter 和 setter,例如:

class MyBase(object):
    def __getattr__(self, key):
         if key.startswith("Get"):
              tail = key[3:]
              if hasattr(self, tail):
                   def getter(self):
                        res = getattr(self, tail)
                        issue_warning()
                        return res
                   return lambda : getter(self)
         raise AttributeError

和二传手类似。

于 2015-08-03T21:11:30.637 回答