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

Dynamic properties

P: n/a
Hello again,

I have a dictionary with the following content :

'LZ': {'type': 'N', 'bytes': '00008'},
'LVI000': {'type': 'N', 'bytes': '000010'}

This could be seen as a interface description to deal with an external
program that needs a 18 Byte communication area. 8 and 18 Bytes have
to be interpreted as a "Number" String representation. eg like
'00000180000000200' means

LZ = 180
and
LVI000 = 200

I am now thinking about doing the following

class a
....

def some_crap () ...

for key in dict.keys ():
setattr (self, key, value)

so that

pgm = a ()
pgm.LZ = 300

would cause the rekonstruktion of the byte field. ===>> Properties

My first try is :

fget = lambda self: mygetattr(self, attrname)
fset = lambda self, value: mysetattr (self, attrname, value)
fdel = lambda self: mydelattr(self, attrname)

# fget, fset, fdel are used to reconstruct the byte field

setattr (self, key, property (fget, fset, fdel))

:-) This inserts me

pgm.LZ and pgm.LVI000 but when trying to access

print pgm.LZ

it gives me

<property object at 0x4028102c>

What am I doing wrong here

Regards

Michael
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
michael wrote:
My first try is :

fget = lambda self: mygetattr(self, attrname)
fset = lambda self, value: mysetattr (self, attrname, value)
fdel = lambda self: mydelattr(self, attrname)

# fget, fset, fdel are used to reconstruct the byte field

setattr (self, key, property (fget, fset, fdel))


setattr creates entries in the instance dictionary of the object that is passed
in. Properties need to be stored in the object type's dictionary in order to
work their magic. I also believe it is required that the class be a new-style class.

So try something like (Python 2.4):

Py> def mygetattr(self, attr):
.... print "Getting %s from %s" % (str(attr), str(self))
....
Py> def mysetattr(self, attr, value):
.... print "Setting %s to %s on %s" % (str(attr), str(value), str(self))
....
Py> def mydelattr(self, attr):
.... print "Deleting %s from %s" % (str(attr), str(self))
....
Py> class C(object):
.... @classmethod
.... def make_properties(cls, attrs):
.... for attr in attrs:
.... # Use default arguments to bind attr *now*, not at call time
.... def _get(self, attr=attr):
.... return mygetattr(self, attr)
.... def _set(self, value, attr=attr):
.... mysetattr(self, attr, value)
.... def _del(self, attr=attr):
.... mydelattr(self, attr)
.... setattr(cls, attr, property(_get, _set, _del))
....
Py> properties = ["x", "y"]
Py> C.make_properties(properties)
Py> C.x
<property object at 0x00A9D3F0>
Py> c = C()
Py> c.x
Getting x from <__main__.C object at 0x00A9A990>
Py> c.x = 1
Setting x to 1 on <__main__.C object at 0x00A9A990>
Py> del c.x
Deleting x from <__main__.C object at 0x00A9A990>
Py> c.y
Getting y from <__main__.C object at 0x00A9A990>
Py> c.y = 1
Setting y to 1 on <__main__.C object at 0x00A9A990>
Py> del c.y
Deleting y from <__main__.C object at 0x00A9A990>

The decorator syntax is the only 2.4'ism I'm aware of in that code, so porting
to 2.3 or even 2.2 shouldn't be an issue.

Cheers,
Nick.

--
Nick Coghlan | nc******@email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #2

P: n/a
On Fri, 2005-01-21 at 06:43 -0800, michael wrote:
setattr (self, key, property (fget, fset, fdel)) it gives me

<property object at 0x4028102c>

What am I doing wrong here


Properties must be defined in the class, not the instance, to work as
expected. (Edit: Nick Coghlan explained this more accurately).

You can dynamically generate properties in a metaclass or class factory,
and you can add them to a class after the class is created (even from an
instance of that class). If you add properties to an instance of a class
rather than the class its self, though, you won't get the expected
results.
..class Fred(object):
.. def __init__(self):
.. self._name = 'fred'
.. def getname(self):
.. return self._name
.. def setname(self, newname):
.. self._name = newname
.. name = property(getname, setname)
..
..f = Fred()
..print f.name
..
..# Works:
..class Fred2(object):
.. def __init__(self):
.. self._name = 'fred2'
.. def getname(self):
.. return self._name
.. def setname(self, newname):
.. self._name = newname
..
..Fred2.name = property(Fred2.getname, Fred2.setname)
..f2 = Fred2()
..print f2.name
..
..# Won't work:
..class Fred3(object):
.. def __init__(self):
.. self._name = 'fred3'
.. def getname(self):
.. return self._name
.. def setname(self, newname):
.. self._name = newname
..
..f3 = Fred3()
..f3.name = property(f3.getname, f3.setname)
..print f3.name
..
..# Also won't work
..f3 = Fred3()
..f3.name = property(Fred3.getname, Fred3.setname)
..print f3.name
..
..# This will work, though, because while it adds the property
..# after the instance is created, it adds it to the class not
..# the instance.
..f3 = Fred3()
..Fred3.name = property(Fred3.getname, Fred3.setname)
..print f3.name

The chances are that whatever you want to do with dynamically created
properties is better done with __getattr__ and __setattr__ instead.

If they don't fit the bill, you can add properties to the class from its
instances. I intensely dislike this though, personally. I'd want to look
into using a class factory or metaclass to do the job if __getattr__ and
__setattr__ are insufficient or unacceptable.

--
Craig Ringer

Jul 18 '05 #3

P: n/a
On Fri, 21 Jan 2005 23:27:28 +0800, Craig Ringer wrote:
The chances are that whatever you want to do with dynamically created
properties is better done with __getattr__ and __setattr__ instead.


Rather than post my own comment, I'd like to highlight this, emphasize it,
and underline it twice. The two other repliers I see were nice to explain
how to do what you were trying to do, but you probably shouldn't do it
that way.

class DictWrap(object):
def __init__(self, dictToWrap):
self.__dict__['dictToWrap'] = dictToWrap
def __getattr__(self, key):
return self.__dict__['dictToWrap'][key]
def __setattr__(self, key, value):
self.__dict__['dictToWrap'][key] = value
def __delattr__(self, key):
del self.__dict__['dictToWrap'][key]

Note the direct use of __dict__, which bypasses the *attr machinery.

This implements a "full" dict wrap; adjust as needed. Be sure to read
about *attr in the Python manual so you understand what they do. You can
do more in getattr if you want, but it doesn't sound like you want much
else.

Python 2.3.4 (#1, Oct 26 2004, 20:13:42)
[GCC 3.4.2 (Gentoo Linux 3.4.2-r2, ssp-3.4.1-1, pie-8.7.6.5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
class DictWrap(object): .... def __init__(self, dictToWrap):
.... self.__dict__['dictToWrap'] = dictToWrap
.... def __getattr__(self, key):
.... return self.__dict__['dictToWrap'][key]
.... def __setattr__(self, key, value):
.... self.__dict__['dictToWrap'][key] = value
.... def __delattr__(self, key):
.... del self.__dict__['dictToWrap'][key]
.... a = {'LV1': .5, 'LV10': 5, 'LV100': 50}
d = DictWrap(a)
d.LV1 0.5 d.LV1 = "Hello!"
d.LV5 = 2.5
d.__dict__ {'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV100': 50, 'LV1': 'Hello!'}} del d.LV100
d.__dict__ {'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV1': 'Hello!'}}

Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.