你如何以编程方式获得属性错误的目标?

时间:2012-03-31 16:34:56

标签: python

我想做类似的事情:

class Foo:
    def __repr__(self):
        return 'an instance of Foo'

try:
    print(Foo().baz)
except AttributeError as err:
    print('target:', err.target)
    print('name:', err.name)

并获得

的输出
target: an instance of Foo
name: baz

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:1)

如果您控制编写类,请进行自定义异常:

class CustomAttributeError(Exception):
    def __init__(self,object,attribute):
        self.object = object
        self.attribute = attribute
    def __str__(self):
        return "{} has no attribute '{}'".format(self.object,self.attribute)

class Foo(object):
    def __getattr__(self,n):
        raise CustomAttributeError(self,n)


a = Foo()
b = Foo()
c = Foo()

a.x=1
b.x=1

try:
    a.x
    b.x
    c.x
except CustomAttributeError as e:
    # Catch this missing attribute and give it a value
    print e
    setattr(e.object,e.attribute,5)

print c.x

输出

<x.Foo object at 0x031478D0> has no attribute 'x'
5

答案 1 :(得分:0)

不幸的是,AttributeError没有以有用的方式传递这些信息。您有两种选择:

  1. 使用r"object has no attribute '([^']+)'"这样的正则表达式解析消息;或
  2. 使用getattr通过字符串varname = 'baz'; print getattr(Foo(), varname)访问变量。这样,您就可以检查varname
  3. 的内容