getattr(object,' name',False)v.s. hasattr(对象,'名称')

时间:2017-11-13 16:07:40

标签: python django

我正在学习通过探索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

似乎hasattr简短易读。

关于他们的比较的问题没有涵盖这一点。 Python hasattr vs getattr - Stack Overflow

在此上下文中应用getattr()是一种更好的做法吗?

1 个答案:

答案 0 :(得分:2)

hasattrgetattr执行不同的操作,在这种情况下不可互换。

考虑将name值设置为空字符串的情况。 hasattr(self, 'name')将返回True,而getattr(self, 'name', False)将返回该空字符串 - 在布尔上下文中评估为False

要替换getattr电话,您需要if hasattr(self, 'name') and self.name:之类的内容,它会执行两次属性查找,而不是一次。