By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,772 Members | 919 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,772 IT Pros & Developers. It's quick & easy.

Dictionary value is property()

P: 1
I'm trying to subclass a dict object to create an object where some key values = 'property(fget, fset, fdel, doc)'. For some reason when I get the dictionary key a 'property object' is return instead of the result of the 'fget' function.

Expand|Select|Wrap|Line Numbers
  1. class mydict(dict):
  2.  
  3.     def __init__(self, arg):
  4.         self['a'] = arg
  5.         self['b'] = property(self.get_b)
  6.  
  7.     def get_b(self):
  8.         return self['a']
  9.  
  10. d = mydict(5)
  11.  
  12. print d['a'] # Returns 5
  13. print d['b'] # Incorrect. Returns <property obeject>. Should return 5.
  14. print d['b'].fget() # Returns 5. Correct
  15.  
Nov 17 '08 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
Function property should work something like this:
Expand|Select|Wrap|Line Numbers
  1. class mydict(dict):
  2.  
  3.     def __init__(self, arg):
  4.         self['a'] = arg
  5.         self.set_b()
  6.  
  7.     def set_b(self):
  8.         self['b'] = self['a']
  9.  
  10.     def get_b(self):
  11.         return self['a']
  12.  
  13.     b = property(set_b, get_b)
  14.  
  15. d = mydict(5)
Expand|Select|Wrap|Line Numbers
  1. >>> d['a']
  2. 5
  3. >>> d['b']
  4. 5
  5. >>> d['a'] = 12
  6. >>> d['b']
  7. 5
  8. >>> d.set_b()
  9. >>> d['b']
  10. 12
  11. >>> d['b']=100
  12. >>> d['b']
  13. 100
  14. >>> 
Calling property is returning a property object and assigning it to key 'b' in your code.
Nov 17 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.