मैं अपना खुद का कंटेनर लिख रहा हूं, जिसे विशेषता कॉल द्वारा अंदर एक शब्दकोश तक पहुंच प्रदान करने की आवश्यकता है। कंटेनर का विशिष्ट उपयोग इस तरह होगा:
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")
या उनमें से एक का उपयोग करने के लिए और इस तरह से एक ब्लॉक पकड़ने की कोशिश करें:
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:। तथास्तु।