how-to do black magic (using metaclass?)

Adam Groszer adamg at mailbox.hu
Fri May 16 07:38:55 EDT 2003


----- Original Message -----
From: "Adam Groszer" <adamg at mailbox.hu>
To: "Tutor at Python. Org" <tutor at python.org>
Sent: Friday, May 16, 2003 9:13 AM
Subject: [Tutor] how-to do black magic


> Dear All,
>
> How-to do the following.
> I have a list of properties let's say in a text file.
> From this list I'd like to create a class's properties and getter/setter
> methods with a metaclass.
> Is this possible? How?
>
> example:
>
> text file:
> Name
> Value
>
> class:
> class sample(base):
> def setName(self, val):
> self.__Name=val
> def getName(self):
> return self.__Name
> Name = property(getName, setName, None, 'this is my Name')
> def setValue(self, val):
> self.__Value=val
> def getValue(self):
> return self.__Value
> Value = property(getValue, setValue, None, 'this is my Value')
>
> something like this, or likely behavior
>
> Adam
>

The recipe

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768

and its (long) discussion should give you a head start.

But from what I gather from your specs, you need only a name to specfiy a
property, that consists simply in a setting/getting from a "private"
attribute. Are you sure you need black magic for just this? Isn't there a
simpler way to accomplish whatever you are trying to do, ditching properties
altogether? Tell us a little more about your problem.

Also, you may have more luck in the python list for this more advanced
stuff, you have a wider audience.

All the best,
G. Rodrigues

---------------------------------------

Thank you,

The problem is more sophisticated, but this is my 'basic' problem currently.

point zero: I'm not sure, if the metaclass is the best solution for this.

I'm lazy :-).
I thought instead of writing always the getter/setter methods, the metaclass
(??) should do it.  Or let's say at a later point I will store the data in a
dictionary, not in private properties.

But as second point I'll need some kind of meta-information about 'my'
properties. Using some kind of list to specify them is the most simple
solution.
Now either
1. I write the list, 'something' prepares the class
2. I prepare the class, 'something' prepares the list
I think the first solution looks better.

(I'm thinking of a 'system' which will read/write the objects from/to a
relational database and therefore I will need much more information about
one property.)

I think to create a half-way functional class from a list of properties lies
in a metaclass.
Again, I'm not 100% sure :-)

Adam






More information about the Python-list mailing list