आह, यह सटीक कोड पर निर्भर करता है। आपके दो टूल्स:
- हैशर (ओबीजे, 'एटीआर') सही है अगर केवल और अगर obj.attr मौजूद है तो सही हो जाता है।
- getattr (obj, 'attr', other_value) obj.attr रिटर्न यदि वह मौजूद है, और other_value
- कोशिश एक = obj.attr/विफलता()/बाकी do_something को छोड़कर (क) जब प्रदर्शन पठनीयता धड़कता है।
अधिकतर सामान्य मामलों रहे हैं:
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)
बेहतर, पूरी प्रक्रिया को समझने के लिए इस स्निपेट को देखो:
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
जो इस आउटपुट है:
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'
स्रोत
2010-03-11 21:35:07
"कम से कम नहीं के प्रदर्शन में, IMO"। आपको शायद इसे मापना चाहिए। आप पाएंगे कि पायथन अपवाद बहुत तेज़ हैं। –
यदि यह वास्तव में एक बाधा है (शायद नहीं), प्रदर्शन भी आम मामले पर निर्भर करता है - क्या विशेषता आमतौर पर मौजूद होती है, या क्या यह आमतौर पर मौजूद नहीं होती है? – orip