问题描述
在 Python 中,当我在 @property
装饰器上调用 hasattr
时,hasattr
函数实际上运行了 @property
代码块.
In Python when I call the hasattr
on a @property
decorator the hasattr
function actually runs the @property
code block.
例如一个类:
class GooglePlusUser(object):
def __init__(self, master):
self.master = master
def get_user_id(self):
return self.master.google_plus_service.people().get(userId='me').execute()['id']
@property
def profile(self):
# this runs with hasattr
return self.master.google_plus_service.people().get(userId='me').execute()
运行以下代码调用 profile 属性并实际进行调用:
Running the following code calls the profile property and actually makes the call:
#Check if the call is an attribute
if not hasattr(google_plus_user, call):
self.response.out.write('Unknown call')
return
为什么?如何在不进行 api 调用的情况下解决此问题?
Why? How can I solve this without making the api call?
推荐答案
hasattr()
通过实际检索属性来工作;如果抛出异常 hasattr()
返回 False
.这是因为这是知道属性是否存在的唯一可靠方法,因为有很多动态方法可以在 Python 对象上注入属性(__getattr__
、__getattribute__
、属性
对象、元类等).
hasattr()
works by actually retrieving the attribute; if an exception is thrown hasattr()
returns False
. That's because that is the only reliable way of knowing if an attribute exists, since there are so many dynamic ways to inject attributes on Python objects (__getattr__
, __getattribute__
, property
objects, meta classes, etc.).
来自 hasattr()
文档:
From the hasattr()
documentation:
这是通过调用getattr(object, name)
并查看它是否引发异常来实现的.
如果您不希望在执行此操作时调用某个属性,则不要使用 hasattr
.使用 vars()
(返回实例字典)或 dir()
(它还为您提供类的名称列表).
If you don't want a property to be invoked when doing this, then don't use hasattr
. Use vars()
(which returns the instance dictionary) or dir()
(which gives you a list of names on the class as well).
这篇关于为什么 hasattr 会执行@property 装饰器代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!