473,387 Members | 1,844 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Dynamic properties

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
3 2237
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Guy Harwood | last post by:
Hi, I have designed a textbox that inherits from the System.Windows.Forms.Textbox control. when the control is readonly the back color changes to a light blue to indicate that it is frozen. ...
1
by: jm | last post by:
I am using (trying) dynamic properties to store a database connection. However, I don't have a connection object on the form. I just do a OdbcConnection in my code. So I can't use the VS IDE to...
2
by: Codex Twin | last post by:
Hi I am designing a class (Q) which will contain provision for dynamic complex properties. For example, these properties could be any or all of the following complex properties: a)...
1
by: sleigh | last post by:
Hello, I'm building a web application that will build a dynamic form based upon questions in a database. This form will have several different sections that consist of a panel containing one to...
5
by: Nate | last post by:
Good Morning All, What we have is a dynamic business object that has varying numbers and types of properties. What it models is a generic saleable product. Not all products have the same...
3
by: cwertman | last post by:
I have a question regarding dynamic properties. I have an Object say Account --Id --Prefix --Fname --Lname --Suffix
5
by: cwertman | last post by:
I have a question regarding dynamic properties. I have an Object say Account --Id --Prefix --Fname --Lname --Suffix
0
by: vnu | last post by:
Hi, Hi, I am working in .net emvironment using vs2005 and vb.net as the language. In one of my project, I need to display the properties of a com object which has dynamic properties(late bind...
3
by: creative1 | last post by:
Here is how you create a complex data report that involves parent and child commands and you can update information at runtime. Its pretty straight forward to work with simple queries; however,...
15
by: EDBrian | last post by:
My problem is this. Our clients create different fields they want to collect and we allow them build dynamic filters, reports etc... We run some TSQL to actually create the column and all works...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.