【问题标题】:Python AttributeError raised [closed]引发 Python AttributeError [关闭]
【发布时间】:2015-12-17 20:42:54
【问题描述】:

我遇到了以下 Python 代码的“AttributeError”:

Def SomeFunc(Self):
    ....
    setattr(Self, "_Some_Attribute", Data)
    ....
    if hasattr(Self, "_Some_Attribute"):
        delattr(Self, "_Some_Attribute")
    ....

在 hasattr 测试为阳性后,立即在 delattr 行上引发 AttributeError。恐慌非常罕见。我会说几百次。

SomeFunc() 可以从多个线程调用。是否有可能在第一个线程测试 hasattr 为阳性后,另一个线程进入 hasattr 和 delattr 以删除“_Some_Attribute”?

【问题讨论】:

  • 请发布实际代码。
  • 另外,请检查重复的stackoverflow.com/questions/1120927/…
  • hasattrdelattr 都是小写的。投票结束是错字。
  • 抱歉打错字了。实际代码是: if hasattr(Self, "_Some_Attribute"): delattr(Self, "_Some_Attribute")
  • 在您提到的另一个答案中“恐慌非常罕见。我会说几百次。”这是一个多线程应用程序吗?在您的真实代码中,hasattrdelattr 之间是否有更多可能出现逻辑错误的处理?就目前而言,您的问题无法重现。

标签: python


【解决方案1】:

当查找对象的属性时,python 首先查找self,然后查找类命名空间。因此,实例变量和类变量都通过了hasattr 测试。删除属性时并非如此。类变量不会被删除。

class C(object):

    classvar = 'foo'

    def __init__(self):
        self.instancevar = 'bar'

c = C()
print('hasattr sees instance and class vars', hasattr(c, 'classvar'), hasattr(c, 'instancevar'))
print('delete instance is fine')
delattr(c, 'instancevar')
print('but classvar is not')
delattr(c, 'classvar')

运行时会报错

hasattr sees instance and class vars True True
delete instance is fine
but classvar is not
Traceback (most recent call last):
  File "u.py", line 13, in <module>
    delattr(c, 'classvar')
AttributeError: classvar

编辑

使用修改后的代码,我无法再重现。我下面的测试用例没有错误。

class C(object):
    def test(self):
        setattr(self, '_foo', 'bar')
        if hasattr(self, '_foo'):
            delattr(self, '_foo')
C().test()
print("Test Passed")

【讨论】:

  • 谢谢。这真的很高兴知道。但是,我不认为这是我的情况。请查看我发布的实际代码。
【解决方案2】:

目前尚不清楚您的情况出现问题的原因。您提供的代码 sn-ps 不足以进行结论性分析。

不过,还是有办法的!

代替:

if hasattr(Self, "_Some_Attribute"):
    delattr(Self, "_Some_Attribute")

这样做:

try:
    delattr(Self, "_Some_Attribute")
except AttributeError:
    # here you choose what you want to do, some options:
    pass
    print 'delattr failed' if hasattr(Self, "_Some_Attribute") else 'ok'
    assert not hasattr(Self, "_Some_Attribute")

It is easier to ask for forgiveness than permission.

【讨论】:

    猜你喜欢
    • 2014-04-08
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多