2012-07-17 15 views
12

से एक पायथन शब्दकोश में एक विशेषता जोड़ना मैं सोच रहा था कि क्या आप एक अजगर शब्दकोश में एक अटूट जोड़ सकते हैं।मानक लाइब्रेरी

class myclass(): 
    def __init__(): 
    self.mydict = {} #initialize a regular dict 
    self.mydict.newattribute = "A description of what this dictionary will hold" 
    >>>AttributeError: 'dict' object has no attribute 'newattribute' 
    setattr(self.mydict,"attribute","A description of what this dictionary will hold" 
    >>>AttributeError: 'dict' object has no attribute 'newattribute' 

क्या डॉट क्लास की प्रतिलिपि बनाने और कन्स्ट्रक्टर को अधिभारित किए बिना मेरी वर्णन विशेषता को तुरंत जोड़ने के लिए वैसे भी है। मैंने सोचा कि यह आसान होगा, लेकिन मुझे लगता है कि मैं गलत था।

धन्यवाद, जम्मू

उत्तर

25

बस dict से निकाले जाते हैं:

class MyDict(dict): 
    pass 

MyDict के उदाहरण कस्टम हो सकता है विशेषताओं:

>>> d = MyDict() 
>>> d.my_attr = "whatever" 
>>> d.my_attr 
'whatever' 
संबंधित मुद्दे