【发布时间】:2017-11-13 16:07:40
【问题描述】:
我正在通过探索 Django 源代码学习编写专业代码。
在django.urls.resolvers | Django documentation | Django 中,内容如下:
class LocaleRegexProvider(object):
def describe(self):
description = "'{}'".format(self.regex.pattern)
if getattr(self, 'name', False):
description += " [name='{}']".format(self.name)
return description
我假设getattr(self, 'name', False): 可以替换为更易读的代码hasattr(self, 'name')
例如
In [22]: if getattr(str,'split',False):
...: print("Str has 'split' attribute")
...: else:
...: print("Str has not 'split' attribute")
...:
Str has 'split' attribute
In [25]: if getattr(str,'sp',False):
...: print("Str has 'sp' attribute")
...: else:
...: print("Str has not 'sp' attribute")
...:
Str has not 'sp' attribute
至于hasattr
In [23]: if hasattr(str,'split'):
...: print("Str has 'split' attribute")
...: else:
...: print("Str has not 'split' attribute")
...:
Str has 'split' attribute
In [24]: if hasattr(str,'sp'):
...: print("Str has 'sp' attribute")
...: else:
...: print("Str has not 'sp' attribute")
...:
Str has not 'sp' attribute
似乎hasattrshort 和可读。
关于他们的比较有一个问题,但没有涉及到这一点。 Python hasattr vs getattr - Stack Overflow
在这种情况下应用getattr() 是否更好?
【问题讨论】: