473,883 Members | 1,679 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

creating many similar properties


I understand how to create a property like this:

class RC(object):
def _set_pwm(self, v):
self._pwm01 = v % 256
def _get_pwm(self):
return self._pwm01
pwm01 = property(_get_p wm, _set_pwm)
But what if I have a whole bunch of these pwm properties?

I made this:

class RC(object):
def _makeprop(name) :
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop)
return property(_get, _set)

pwm01 = _makeprop('pwm0 1')
pwm02 = _makeprop('pwm0 2')
Not too bad, except for having to repeat the name.

I would like to just have a list of pwm names and
have them all set up like that. It would be nice if
each one was set to a default value of 127 also....

Any thoughts?

Thanks for your time.
Oct 18 '06 #1
17 1962
Lee Harr wrote:
I understand how to create a property like this:

class RC(object):
def _set_pwm(self, v):
self._pwm01 = v % 256
def _get_pwm(self):
return self._pwm01
pwm01 = property(_get_p wm, _set_pwm)
But what if I have a whole bunch of these pwm properties?

I made this:

class RC(object):
def _makeprop(name) :
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop)
return property(_get, _set)

pwm01 = _makeprop('pwm0 1')
pwm02 = _makeprop('pwm0 2')
Not too bad, except for having to repeat the name.

I would like to just have a list of pwm names and
have them all set up like that. It would be nice if
each one was set to a default value of 127 also....

Any thoughts?

Thanks for your time.
You want a "class factory". This can either be the esoteric "metaclass"
(using "type"), which one can only understand for moments at a time, or
something more grounded in intuition, or, a combo (for fun). You can
probably tighten this a little, but this is the idea:

def c_factory(cname , pname, num, modulus, default):
def accessorize(pro p):
def _get(self):
return getattr(self, prop)
def _set(self, v):
v_new = v % modulus
setattr(self, prop, v_new)
return (_get, _set)
def _init(self):
for i in xrange(num):
setattr(self, '%s%s' % (pname,i), default)
_C = type(cname, (object,), {'__init__':_in it})
for i in xrange(num):
prop = '_%s%s' % (pname, i)
setattr(_C, '%s%s' % (pname, i), property(*acces sorize(prop)))
return _C

E.g.:
pydef c_factory(cname , pname, num, modulus, default):
.... def accessorize(pro p):
.... def _get(self):
.... return getattr(self, prop)
.... def _set(self, v):
.... v_new = v % modulus
.... setattr(self, prop, v_new)
.... return (_get, _set)
.... def _init(self):
.... for i in xrange(num):
.... setattr(self, '%s%s' % (pname,i), default)
.... _C = type(cname, (object,), {'__init__':_in it})
.... for i in xrange(num):
.... prop = '_%s%s' % (pname, i)
.... setattr(_C, '%s%s' % (pname, i), property(*acces sorize(prop)))
.... return _C
....
pyBob = c_factory('Bob' , 'bob', 4, 256, 128)
pyb = Bob()
pyb.bob0
128
pyb.bob1
128
pyb.bob1 = 258
pyb.bob1
2
pyb.bob3
128
pydir(b)

['__class__',
'__delattr__',
'__dict__',
'__doc__',
'__getattribute __',
'__hash__',
'__init__',
'__module__',
'__new__',
'__reduce__',
'__reduce_ex__' ,
'__repr__',
'__setattr__',
'__str__',
'__weakref__',
'_bob0',
'_bob1',
'_bob2',
'_bob3',
'bob0',
'bob1',
'bob2',
'bob3']
pyBob
<class '__main__.Bob'>


--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Oct 18 '06 #2
In <n2************ *****@news01.ro c.ny>, Lee Harr wrote:
But what if I have a whole bunch of these pwm properties?

I made this:

class RC(object):
def _makeprop(name) :
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop)
return property(_get, _set)

pwm01 = _makeprop('pwm0 1')
pwm02 = _makeprop('pwm0 2')
Not too bad, except for having to repeat the name.

I would like to just have a list of pwm names and
have them all set up like that. It would be nice if
each one was set to a default value of 127 also....

Any thoughts?
Use `__getattr__()` and `__setattr__()` methods and a dictionary of names
mapped to values and another that maps the names to default values for the
modulo operation.

Ciao,
Marc 'BlackJack' Rintsch
Oct 18 '06 #3
Lee Harr wrote:
I understand how to create a property like this:

class RC(object):
def _set_pwm(self, v):
self._pwm01 = v % 256
def _get_pwm(self):
return self._pwm01
pwm01 = property(_get_p wm, _set_pwm)
But what if I have a whole bunch of these pwm properties?

I made this:

class RC(object):
def _makeprop(name) :
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop)
return property(_get, _set)

pwm01 = _makeprop('pwm0 1')
pwm02 = _makeprop('pwm0 2')
Not too bad, except for having to repeat the name.

I would like to just have a list of pwm names and
have them all set up like that. It would be nice if
each one was set to a default value of 127 also....

Any thoughts?
Yes, what about this?

import sys

def defprop(name, default=127):
loc = sys._getframe(1 ).f_locals
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop, default)
loc[name] = property(_get, _set)

class RC(object):
defprop('pwm01' )
defprop('pwm02' )

rc = RC()

print rc.pwm01 # 127
print rc.pwm02 # 127
rc.pwm02 = 1312
print rc.pwm02 # 32

This is a bit hackish, but I would prefer this over a metaclass
solution. since it does not add
any hidden magic to your class.

Michele Simionato

Oct 18 '06 #4

Lee Harr wrote:
I understand how to create a property like this:

class RC(object):
def _set_pwm(self, v):
self._pwm01 = v % 256
def _get_pwm(self):
return self._pwm01
pwm01 = property(_get_p wm, _set_pwm)
But what if I have a whole bunch of these pwm properties?

I made this:

class RC(object):
def _makeprop(name) :
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop)
return property(_get, _set)

pwm01 = _makeprop('pwm0 1')
pwm02 = _makeprop('pwm0 2')
Not too bad, except for having to repeat the name.

I would like to just have a list of pwm names and
have them all set up like that. It would be nice if
each one was set to a default value of 127 also....

Any thoughts?

The metaclass solution. I use this idiom occasionally, whenever I want
to fiddle with the class dict before letting the type constructor at
it.

class mod256metatype( type):
def __new__(metatyp e,name,bases,cl sdict):
for sym in clsdict.get('__ mod256__',()):
prop = '_%s' % sym
def _set(self,v):
setattr(self,pr op,v%256)
def _get(self):
return getattr(self,pr op)
clsdict[sym] = property(_get,_ set)
return type.__new__(me tatype,name,bas es,clsdict)

class RC(object):
__metaclass__ = mod256metatype
__mod256__ = ["pwm01","pw m02"]
Carl

Oct 18 '06 #5
Michele Simionato wrote:
Lee Harr wrote:
I understand how to create a property like this:

class RC(object):
def _set_pwm(self, v):
self._pwm01 = v % 256
def _get_pwm(self):
return self._pwm01
pwm01 = property(_get_p wm, _set_pwm)
But what if I have a whole bunch of these pwm properties?

I made this:

class RC(object):
def _makeprop(name) :
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop)
return property(_get, _set)

pwm01 = _makeprop('pwm0 1')
pwm02 = _makeprop('pwm0 2')
Not too bad, except for having to repeat the name.

I would like to just have a list of pwm names and
have them all set up like that. It would be nice if
each one was set to a default value of 127 also....

Any thoughts?

Yes, what about this?

import sys

def defprop(name, default=127):
loc = sys._getframe(1 ).f_locals
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop, default)
loc[name] = property(_get, _set)

class RC(object):
defprop('pwm01' )
defprop('pwm02' )

rc = RC()

print rc.pwm01 # 127
print rc.pwm02 # 127
rc.pwm02 = 1312
print rc.pwm02 # 32

This is a bit hackish, but I would prefer this over a metaclass
solution. since it does not add
any hidden magic to your class.
Why is this less hidden or magical than a metaclass ? I'd prefer the
following instead:

from itertools import chain, izip, repeat

def ByteProperties( *names, **defaulted_nam es):
def byte_property(n ame, default):
return property(lambda self: getattr(self, name, default),
lambda self,v: setattr(self, name, v%256))
def make_class(clsn ame, bases, dict):
for name,default in chain(izip(name s, repeat(127)),
defaulted_names .iteritems()):
assert name not in dict # sanity check
dict[name] = byte_property(' _'+name, default)
return type(clsname,ba ses,dict)
return make_class
class RC(object):
__metaclass__ = ByteProperties( 'pwm01', pwm02=64)

rc = RC()
print rc.pwm01, rc.pwm02 # 127 64
rc.pwm01 = 1312
print rc.pwm01, rc.pwm02 # 32 64
George

Oct 18 '06 #6
Carl Banks wrote:
Lee Harr wrote:
I understand how to create a property like this:

class RC(object):
def _set_pwm(self, v):
self._pwm01 = v % 256
def _get_pwm(self):
return self._pwm01
pwm01 = property(_get_p wm, _set_pwm)
But what if I have a whole bunch of these pwm properties?

I made this:

class RC(object):
def _makeprop(name) :
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop)
return property(_get, _set)

pwm01 = _makeprop('pwm0 1')
pwm02 = _makeprop('pwm0 2')
Not too bad, except for having to repeat the name.

I would like to just have a list of pwm names and
have them all set up like that. It would be nice if
each one was set to a default value of 127 also....

Any thoughts?


The metaclass solution. I use this idiom occasionally, whenever I want
to fiddle with the class dict before letting the type constructor at
it.

class mod256metatype( type):
def __new__(metatyp e,name,bases,cl sdict):
for sym in clsdict.get('__ mod256__',()):
prop = '_%s' % sym
def _set(self,v):
setattr(self,pr op,v%256)
def _get(self):
return getattr(self,pr op)
clsdict[sym] = property(_get,_ set)
return type.__new__(me tatype,name,bas es,clsdict)

class RC(object):
__metaclass__ = mod256metatype
__mod256__ = ["pwm01","pw m02"]
There's a subtle common bug here: all _get and _set closures will refer
to the last property only. You have to remember to write "def
_set(self,v,pro p=prop)" and similarly for _get to do the right thing.
By the way, I can't think of a case where the current behavior (i.e.
binding the last value only) is the desired one. Is this just an
implementation wart or am I missing something ?

George

Oct 18 '06 #7
George Sakkis wrote:
>
Why is this less hidden or magical than a metaclass ?
Because it does not use inheritance. It is not going to create
properties on subclasses without
you noticing it. Also, metaclasses are brittle: try to use them with
__slots__, or with non-standard
classes (i.e. extensions classes), or try to use multiple metaclasses.
I wrote a paper
about metaclasses abuses which should be published soon or later; you
can see the draft
here:
http://www.phyast.pitt.edu/~micheles...itializer.html

Michele Simionato

Oct 18 '06 #8
George Sakkis wrote:
>
from itertools import chain, izip, repeat

def ByteProperties( *names, **defaulted_nam es):
def byte_property(n ame, default):
return property(lambda self: getattr(self, name, default),
lambda self,v: setattr(self, name, v%256))
def make_class(clsn ame, bases, dict):
for name,default in chain(izip(name s, repeat(127)),
defaulted_names .iteritems()):
assert name not in dict # sanity check
dict[name] = byte_property(' _'+name, default)
return type(clsname,ba ses,dict)
return make_class
class RC(object):
__metaclass__ = ByteProperties( 'pwm01', pwm02=64)
Notice that you are NOT using a custom metaclass here, you are just
using the metaclass hook
and you will avoid all issues of custom metaclasses. This is exactly
the approach I advocate
in the paper I referred before, so I think your solution is pretty safe
in that respect. Still I
think in this particular problem avoiding the __metaclass__ at all is
possible and it should be
preferred, just for sake of simplicity, not of safety).

Michele Simionato

M

Oct 18 '06 #9

George Sakkis wrote:
Michele Simionato wrote:
import sys

def defprop(name, default=127):
loc = sys._getframe(1 ).f_locals
prop = '_%s' % name
def _set(self, v):
v_new = v % 256
setattr(self, prop, v_new)
def _get(self):
return getattr(self, prop, default)
loc[name] = property(_get, _set)

class RC(object):
defprop('pwm01' )
defprop('pwm02' )

rc = RC()

print rc.pwm01 # 127
print rc.pwm02 # 127
rc.pwm02 = 1312
print rc.pwm02 # 32

This is a bit hackish, but I would prefer this over a metaclass
solution. since it does not add
any hidden magic to your class.

Why is this less hidden or magical than a metaclass ?
Devil's Advocate: he did say "hidden magic TO YOUR CLASS".

If you use a (real) metaclass, then you have the icky feeling of a
class permanently tainted by the unclean metaclass (even though the
metaclass does nothing other than touch the class dict upon creation);
whereas if you use Michele Simionato's hack, the icky feeling of using
a stack frame object goes away after the property is created: you are
left with a clean untainted class.

Personally, the former doesn't make me feel icky at all.
Carl Banks

Oct 18 '06 #10

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

Similar topics

7
8440
by: Simon Edwards | last post by:
Something thats been bugging me for a while... how do you create a namespace that has many children (namespaces) I.e system.io.blah.blah Iv'e done it by creating a class which contains another class. i can see the properties of the first class and the namespace of the second (inner class) but can't see the properties of the 2nd....
4
561
by: Altramagnus | last post by:
I have 30 - 40 type of different window. For each type I need about 20 instances of the window. When I try to create them, I get "Error creating window handle" My guess is there is a maximum number of window handle, because if I reduce to about 2 instances of each window, it can run. But not 20 instances of each window. Does anyone know what the problem is? is it really because it exceeds the maximum number of window handle?
0
1543
by: Sergej Pioch | last post by:
Hello everybody, im trying hard to automate some tasks in a huge windows environment. This lend me to bigger problems while trying to create new global security groups within active directory. First I tried to add the groups as discribed in article "Creating Groups" at Platform SDK: System.DirectoryServices documentation. I figuerd out that something in the article was missing, because groupcreation ended in an error: "A constraint...
1
1232
by: Neil Robbins | last post by:
I have been wondering recently how I would go about creating a control that when selected from the toolbox for use in an application either autoran a wizard for providing it with properties or provided for the selection of an option from the properties window that would run a wizard. I suppose what I envisage would be similar to the AutoFormat option in the Properties menu for the DataGrid Control. Also how could one create something...
2
3063
by: Terrance | last post by:
Can someone please help with a problem that I'm having? I'm trying to create a linklabel in VB.NET 2003 at runtime when a user clicks a button. The app looks in a path for .doc and .pdf files and creates a linklabel for each file name. When running the app the first name is being created but only portions of the string is showing; and also it looks like the remaining is being created but I can't see them it's like their cut off. Here is the...
26
5385
by: nyathancha | last post by:
Hi, How Do I create an instance of a derived class from an instance of a base class, essentially wrapping up an existing base class with some additional functionality. The reason I need this is because I am not always able to control/create all the different constructors the base class has. My problem can be described in code as follows ... /* This is the base class with a whole heap of constructors/functionality*/ public class Animal
0
1979
by: ronscottlangham | last post by:
I am working on a custom WCF EndpoingBehavior that will modify the messages coming in and out of my Service. I am having an error related to the modification of the message in the IEndpointBehavior.AfterReceiveRequest(ref Message request,...) method. In the method that creates a new message, I have something similar to ... /// xmlReader defined with new modified content.... /// 'message' is the original message...
1
1400
by: MMAS | last post by:
I've seen a similar post about this problem but still cannot find an automated solution. Below is the code I'm using to create a website (for IIS 6.0) via C#. once the site is created, it will not serve aspx pages. If I: 1. go to IIS Manager 2. view the properties for the site in question 3. go to the tab 4. click next to the Application Name textbox in the Application Settings area.
2
2332
by: adwest | last post by:
Forgive me if this is a foolish question. I "play" in Access and have only created a few rather simple relational databases. My knowledge and experience is limited. I have no formal training, just picked up a few books and have gone from there... I'm not sure how to relate my question using the accepted shorthand, so I'm afraid this will be a narrative description. I am using Access 2003. The database is for property management. I have...
0
9938
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9791
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11140
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10847
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9572
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7971
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4611
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
2
4218
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3232
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.