python - 如何检查缺少的属性?

标签 python class oop reflection attributes

我必须检查 foo 是否是 myclass 的属性。

现在是我

def myclass():
    try:
        self.foo
    except AttributeError:
        self.foo = 'default'

当我认为我应该做的时候

if not hasattr(self,'foo'):
    self.foo = 'default'

这两种方法之间有什么区别吗?应该首选哪一种?

我正在寻找以下条件:

  • 与多重继承的一致性
  • 跨python版本的可移植性
  • 有限的开销

最佳答案

这两种方法在功能上是等效的。

来自 the hasattr docs :

hasattr(object, name)

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)

the getattr docs说明如下:

getattr(x, 'foobar') is equivalent to x.foobar


关于速度,我的测试表明 hasattr 稍快一些。 100 万次迭代的结果是:

hasattr: 0.6325701880014094 seconds
try:     0.8206841319988598 seconds

除非您正在编写高度优化的代码,否则无需担心这么小的差异。也无需担心与 python 版本的兼容性;属性访问和 hasattr 在每个版本的 python 中都可用。


最后,它归结为偏好。选择您认为更具可读性的那个。

关于python - 如何检查缺少的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49653108/

相关文章:

python - 是否可以在 python 日志记录配置中使用环境变量?

python - 在 python 列表上使用 apply 时出现错误

python - 安排一个 python 脚本在网络服务器上运行

c# - 将 C# 类转换为 JavaScript

wpf - F# 可区分联合和 WPF 数据绑定(bind)

swift - 以更加面向对象的方式根据三个选择之一执行操作

c++ - 我可以使用不同类的函数参数创建高阶函数吗?

python - 如何使用 Python Threading 在线程之间传递参数?

java - 获取我通过参数传递的相同 Java 类实例

java - 使用 OOP 向 ArrayList 添加值