473,545 Members | 2,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

multi-property groups?



I was trying to see if I can implement property groups so I can set and
pass arguemts as dictionaries. I think this will simplify interfacing
to multiple objects and funtions that use a lot of keywords as arguments.

But so far, the the following seems like it's not the most efficient way
to do it. So is there a better way? Is there a way to use properties
to do this same thing?

I'd also like a way to override the dictionary methods __getitem__,
__setitem__, and __delitem__. (Or an equivalent)
Cheers,
Ron
class Pobject(object) :
""" an objects class that can have property groups """
__props__ = {}
def Properties(self , *args):
dct = {}
for i in args[1:]:
dct.setdefault( i,None)
self.__props__[args[0]]=dct
return dct
def __getattr__(sel f, name):
for dct in self.__props__:
if name in self.__props__[dct]:
return self.__props__[dct].__getitem__(na me)
return self.__dict__[name]
def __setattr__(sel f, name, value):
for dct in self.__props__:
if name in self.__props__[dct]:
self.__props__[dct].__setitem__(na me,value)
return
self.__dict__[name] = value

class shapes(Pobject) :
def __init__(self):
self.A = self.Properties ('A', 'square', 'triangle', 'cube')
self.B = self.Properties ('B', 'red', 'blue', 'green')
def show(self, it):
if it == 'shapes':
self.pp(it, self.A) # pass properties as groups!
elif it == 'colors':
self.pp(it, self.B) # have several property groups!
else:
print "I have no %s.\n" % it
def pp(self, it, obj):
print '%s I have:' % it
for item in obj.keys():
print ' %s = %r' % (item,obj[item])
print

box = shapes()
box.square = 10
box.blue = 5
print box.square
print box.blue
print box.green
box.purple = 'violet'
print box.purple
print
box.show('shape s')
box.show('color s')
box.show('flowe rs')
10
5
None
violet

shapes I have:
cube = None
square = 10
triangle = None

colors I have:
blue = 5
green = None
red = None

I have no flowers.
Oct 19 '05 #1
1 1582

This is what I like about Python, there's almost always a way to do it. ;-)

Here's an updated version that I think works, but it could use some review.

Any way to make this better? Should grouped properties share
references to objects?

Cheers,
Ron
"""
Grouped properties:

This need presented it self while programming Tkinter applications where
a lot of keywords are used, but I think it would also be good for
general interface building. The external view is of a single object,
while the internal mechanism keeps the attributes groups so they can be
forwarded easily as **kwds.

class foo(object):
def __init__(self):
self.__setprops __(name, item_1, item_2, ... item_n)
name.__doc__ = 'this is the name group of properties'
def getter():
...
def setter():
...
def remover():
...
name.__getitem_ _ = getter
name.__setitem_ _ = setter
name.__delitem_ _ = remover
The following is as close to getting to as I am able I think.
Only somewhat tested... but it seems to work.
"""
class Pdict(dict):
# we need this so we can override the methods.
__doc__ = "a property dictionary"

class Pobject(object) :
""" an object with grouped properties """
__properties__ = {}
def __setprops__(se lf, *args):
"""
Create a group property
__setprops__(na me, p1, p2, p3, ... pn)

* all arguments are strings to be made into names.
"""
dct = Pdict()
for i in args[1:]:
dct.setdefault( i,None)
self.__properti es__[args[0]] = dct
self.__dict__[args[0]] = dct
def __getattr__(sel f, name):
for dct in self.__properti es__:
if name in self.__properti es__[dct]:
return self.__properti es__[dct].__getitem__(na me)
return self.__dict__[name]
def __setattr__(sel f, name, value):
for dct in self.__properti es__:
if name in self.__properti es__[dct]:
self.__properti es__[dct].__setitem__(na me,value)
return
self.__dict__[name] = value

## A simple example to test it. ##

class shapes(Pobject) :
def __init__(self):

# init the A properties
self.__setprops __('A', 'square', 'triangle', 'cube', 'circle')
self.A.__doc__ = 'These are the "A" properties'
def A_getter(name):
return -self.A[name] # just to show it will
self.A.__getite m__ = A_getter

# init the B properties
self.__setprops __('B', 'red', 'blue', 'green', 'orange')
self.B.__doc__ = 'These are the "B" properties'

def show(self, it):
if it == 'shapes':
self.pprint(sel f.A) # pass properties as groups!
elif it == 'colors':
self.pprint(sel f.B) # have several property groups!
else:
print "I have no %s.\n" % it

def pprint(self, obj):
print obj.__doc__
for item in obj.keys():
print ' %s = %r' % (item,obj[item])
print

box = shapes()

# Set items; no need to now what group
# they are in.
box.cube = 6
box.square = 4
box.triangle = 3
box.circle = 0

# Update a whole group at once with the group name.
box.B.update(bl ue='blue', green='green', red='rose', orange='orange' )
box.red = 'red'

# Get items
print box.square
print box.blue
print box.green

# Show the groups.
box.show('shape s')
box.show('color s')
box.show('flowe rs')

## outputs ##

-4
blue
green
These are the "A" properties
cube = 6
square = 4
triangle = 3
circle = 0

These are the "B" properties
blue = 'blue'
green = 'green'
orange = 'orange'
red = 'red'

I have no flowers.

## end ##

Oct 20 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
4836
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage which cpu shoud do every thread? Sincerely Yours, Pujo
4
4636
by: Frank Jona | last post by:
Intellisense with C# and a multi-file assembly is not working. With VB.NET it is working. Is there a fix availible? We're using VisualStudio 2003 Regards Frank
0
3757
by: frankenberry | last post by:
I have multi-page tiff files. I need to extract individual frames from the multi-page tiffs and save them as single-page tiffs. 95% of the time I receive multi-page tiffs containing 1 or more black and white CCITT4 compressed files (frames) inside the tiff. Every now and then I receive a mixture of black and white CCITT4 and JPEG compressed...
6
8148
by: cody | last post by:
What are multi file assemblies good for? What are the advantages of using multiple assemblies (A.DLL+B.DLL) vs. a single multi file assembly (A.DLL+A.NETMODULE)?
4
17829
by: mimmo | last post by:
Hi! I should convert the accented letters of a string in the correspondent letters not accented. But when I compile with -Wall it give me: warning: multi-character character constant Do the problem is the charset? How I can avoid this warning? But the worst thing isn't the warning, but that the program doesn't work! The program execute...
5
5969
by: Shane Story | last post by:
I can seem to get the dimensions of a frame in a multiframe tiff. After selecting activeframe, the Width/Height is still really much larger than the page's actual dimensions. When I split a TIFF to several PNG files this causes a problem, becuase the resulting image is (the page to the far left and a lot of black space surrounding it and...
5
5723
by: bobwansink | last post by:
Hi, I'm relatively new to programming and I would like to create a C++ multi user program. It's for a project for school. This means I will have to write a paper about the theory too. Does anyone know a good place to start looking for some theory on the subject of multi user applications? I know only bits and pieces, like about...
5
3245
by: dkelly925 | last post by:
Is there a way to add an If Statement to the following code so if data in a field equals "x" it will launch one report and if it equals "y" it would open another report. Anyone know how to modify this? Private Sub cmdPreview_Click() On Error GoTo Err_Handler 'Purpose: Open the report filtered to the items selected in the list box....
0
2302
by: Sabri.Pllana | last post by:
We apologize if you receive multiple copies of this call for papers. *********************************************************************** 2008 International Workshop on Multi-Core Computing Systems (MuCoCoS'08) Barcelona, Spain, March 4 - 7, 2008; in conjunction with CISIS'08. <http://www.par.univie.ac.at/~pllana/mucocos08>...
1
9288
by: mknoll217 | last post by:
I am recieving this error from my code: The multi-part identifier "PAR.UniqueID" could not be bound. The multi-part identifier "Salary.UniqueID" could not be bound. The multi-part identifier "PAR.UniqueID" could not be bound. The multi-part identifier "PAR.PAR_Status" could not be bound. The multi-part identifier "Salary.New_Salary" could not...
0
7682
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7935
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7780
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6009
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5351
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3479
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3465
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1911
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
734
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.