【问题标题】:getattr(object, 'name', False) v.s. hasattr(object,'name')getattr(object, 'name', False) vs. hasattr(对象,'名称')
【发布时间】: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() 是否更好?

【问题讨论】:

    标签: python django


    【解决方案1】:

    hasattrgetattr 做不同的事情,在这种情况下不能互换。

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

    要替换 getattr 调用,您需要类似 if hasattr(self, 'name') and self.name: 的东西,它会执行两个属性查找而不是一个。

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      相关资源
      最近更新 更多