gpt4 book ai didi

python - 是否可以通过Python3中的属性来确定方法是否被调用?

转载 作者:行者123 更新时间:2023-11-30 23:08:16 25 4
gpt4 key购买 nike

摘要

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

详细信息

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

最佳答案

您无法区分 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

关于python - 是否可以通过Python3中的属性来确定方法是否被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31796584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com