ฉันกำลังเขียนคอนเทนเนอร์ของตัวเองซึ่งจำเป็นต้องให้สิทธิ์การเข้าถึงพจนานุกรมภายในด้วยการเรียกแอตทริบิวต์ การใช้งานทั่วไปของคอนเทนเนอร์จะเป็นเช่นนี้:
dict_container = DictContainer()
dict_container['foo'] = bar
...
print dict_container.foo
ฉันรู้ว่ามันอาจงี่เง่าที่จะเขียนบางอย่างเช่นนี้ แต่นั่นเป็นฟังก์ชั่นที่ฉันต้องการ ฉันคิดว่าจะใช้สิ่งนี้ด้วยวิธีต่อไปนี้:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
try:
return self.dict[item]
except KeyError:
print "The object doesn't have such attribute"
ฉันไม่แน่ใจว่าการลอง / ยกเว้นบล็อกเป็นวิธีปฏิบัติที่ดีหรือไม่ดังนั้นจึงควรใช้อีกวิธีหนึ่งhasattr()และhas_key():
def __getattribute__(self, item):
if hasattr(self, item):
return object.__getattribute__(item)
else:
if self.dict.has_key(item):
return self.dict[item]
else:
raise AttributeError("some customised error")
หรือใช้หนึ่งในนั้นและลองใช้ catch block ดังนี้:
def __getattribute__(self, item):
if hasattr(self, item):
return object.__getattribute__(item)
else:
try:
return self.dict[item]
except KeyError:
raise AttributeError("some customised error")
ตัวเลือกแบบไหนที่ไพเราะและสง่างามที่สุด?
if 'foo' in dict_container:จะขอบคุณพระเจ้าหลามให้ สาธุ