Dictionary value is property()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nvj944
    New Member
    • Nov 2008
    • 1

    Dictionary value is property()

    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.

    Code:
    class mydict(dict):
    
        def __init__(self, arg):
            self['a'] = arg
            self['b'] = property(self.get_b)
        
        def get_b(self):
            return self['a']
    
    d = mydict(5)
    
    print d['a'] # Returns 5
    print d['b'] # Incorrect. Returns <property obeject>. Should return 5.
    print d['b'].fget() # Returns 5. Correct
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Function property should work something like this:
    Code:
    class mydict(dict):
    
        def __init__(self, arg):
            self['a'] = arg
            self.set_b()
    
        def set_b(self):
            self['b'] = self['a']
        
        def get_b(self):
            return self['a']
    
        b = property(set_b, get_b)
    
    d = mydict(5)
    Code:
    >>> d['a']
    5
    >>> d['b']
    5
    >>> d['a'] = 12
    >>> d['b']
    5
    >>> d.set_b()
    >>> d['b']
    12
    >>> d['b']=100
    >>> d['b']
    100
    >>>
    Calling property is returning a property object and assigning it to key 'b' in your code.

    Comment

    Working...