I want to subclass a python dictionary to create a new class with dynamic keys. In other words the key value is 'property(fset, fget, fdel, doc)'.

For some reason the when I get the d key, a property object is return instead of the function get_b.

d should return the value of d but instead returns a property object
d.fget() returns the value i want.

Where did I go wrong?

class mydict(dict):

    def __init__(self, arg):
        self['a'] = arg
        self['b'] = property(self.get_b)
    
    def get_b(self):
        return self['a']
#--------------------EXAMPLE--------------------

d = mydict(5)
print 'a = ', d['a'] # Returns 5
print 'b = ', d['b'] # Incorrect. Returns <property obeject>. Should return 5.
print 'fget =', d['b'].fget() # Correct. Returns 5.
>>> class mydict(dict):
...     def __init__(self, arg):
...         self['a'] = arg
...         self['b'] = self.get_b()
... 
...     def get_b(self):
...         return self['a']
...     
>>> d3 = mydict(6)
>>> d3['b']
6

Here's the help for property:

>>> help(property)
Help on class property in module __builtin__:

class property(object)
| property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
|
| fget is a function to be used for getting an attribute value, and likewise
| fset is a function for setting, and fdel a function for del'ing, an
| attribute. Typical use is to define a managed attribute x:
| class C(object):
| def getx(self): return self.__x
| def setx(self, value): self.__x = value
| def delx(self): del self.__x
| x = property(getx, setx, delx, "I'm the 'x' property.")
|
| Methods defined here:
|
| __delete__(...)
| descr.__delete__(obj)
|
| __get__(...)
| descr.__get__(obj[, type]) -> value
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __init__(...)
| x.__init__(...) initializes x; see x.__class__.__doc__ for signature
|
| __set__(...)
| descr.__set__(obj, value)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| fdel
|
| fget
|
| fset
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object at 0x1E1CB838>
| T.__new__(S, ...) -> a new object with type S, a subtype of T

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.