"literal" objects

Pekka Pessi Pekka.Pessi at nokia.com
Sat Jan 3 17:33:33 CET 2004


"Moosebumps" <purely at unadulterated.nonsense> writes:
>mystruct x = { 3, 5.0f };
>mystruct y = { 5, 15.0f };

>These are just "data".  Obviously in python you could just write an init
>function like this:

>x.a = 3;
>x.b = 5;

>y.a = 5;
>y.b = 15;

>And that would work fine, but the programmer in me says that that's a pretty
>inelegant way to do it.  Why execute code when all you need is to put data
>in the program?

This depends what you plant to do. Easiest way to initialize the
__dict__ is with code something like this:

class AnyStruct:
    def __init__(self, **kw):
	self.__dict__.update(kw)

The ** in the __init__ signature means that it puts all named arguments
in the dictionary kw. 

You can then use your structure class like this:

x = AnyStruct(a = 3, b = 5)

Of course, this is "nice" trick to utilize whenever you initialize an
instance.

If you have some mandatory argument, you can require that callers sets
them with

class MyStruct:
    def __init__(self, a, b, **kw):
	self.a = a
	self.b = b
	self.__dict__.update(kw)

then

x = MyStruct(3, 5)

does same as

x = MyStruct(a = 3, b = 5)

but the latter is a bit more readable.

--Pekka



More information about the Python-list mailing list