Skip to main content
 首页 » 编程设计

python之如何以编程方式获取属性错误的目标

2025年05月04日13tuyile006

我想做这样的事情:

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 

有办法吗?

请您参考如下方法:

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

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