Ah, nó phụ thuộc vào mã chính xác. Hai công cụ của bạn:
- hasattr (obj, 'attr') trả về Đúng nếu và chỉ khi obj.attr tồn tại.
- getattr (obj, 'attr', other_value) trả về obj.attr nếu nó tồn tại, else else_value
- try a = obj.attr/trừ thất bại()/else do_something (a) khi hiệu suất có thể đọc được.
Dưới đây là những trường hợp phổ biến nhất:
the_name = getattr(user, 'name', '<Unknown User>')
user.name = getattr(user, 'name', '<Unknown User>')
if not hasattr(name, 'user'):
try_asking_again()
name = user.name if hasattr(user, 'name') else do_expensive_name_lookup(user)
Để hiểu rõ hơn về toàn bộ quá trình, nhìn vào đoạn mã này:
class Thing():
def __init__(self):
self.a = 'A'
def __getattr__(self, attr):
if attr == "b":
return "B"
else:
raise AttributeError("Thing instance has no attribute '" + attr + "'")
item = Thing()
print "hasattr(a) is " + str(hasattr(item, "a"))
print "a is " + item.a
print "hasattr(b) is " + str(hasattr(item, "b"))
print "b is " + item.b
out = "c is " + item.c if hasattr(item, "c") else "No C"
print out
print "and c is also " + getattr(item, "c", "Not Assigned")
print "c throws an Attribute exception " + item.c
trong đó có sản lượng này:
hasattr(a) is True
a is A
hasattr(b) is True
b is B
No C
and c is also Not Assigned
Traceback (most recent call last):
File "attr_snippet.py", line 23, in <module>
print "c throws an Attribute exception " + item.c
File "attr_snippet.py", line 9, in __getattr__
raise AttributeError("Thing instance has no attribute '" + attr + "'")
AttributeError: Thing instance has no attribute 'c'
Nguồn
2010-03-11 21:35:07
"Ít nhất không trong hoạt động, IMO". Có lẽ bạn nên đo nó. Bạn sẽ thấy rằng các ngoại lệ Python rất nhanh. –
Nếu nó thực sự là một nút cổ chai (có thể không), hiệu suất cũng phụ thuộc vào trường hợp phổ biến - thuộc tính thường tồn tại, hay nó thường không tồn tại? – orip