Static Class Initialization Question.
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Fri Jul 4 08:26:01 EDT 2008
Thomas Troeger a écrit :
> Hello,
>
> I have a class that looks like this:
>
> class A(object):
> def __init__(self, a=0, b=1):
> self.a, self.b=a, b
>
> def __str__(self):
> return "%s(%d,%d)" % (type(a).__name__, self.a, self.b)
Given the output example you give, I assume there's a typo here and you
meant:
return "%s(%d,%d)" % (type(self).__name__, self.a, self.b)
> I want to have a list of such classes instantiated automatically on
> startup of my program. My current (most probably clumsy) implementation
> looks like this:
>
> bla=[A(x[0], x[1]) for x in ((1, 2), (3, 4))]
Not clumsy at all, and almost perfectly pythonic. The only improvment I
can think of is:
bla = [A(*args) for args in ((1,2), (3,4))]
> giving the following:
>
> >>> map(str, bla)
> ['A(1,2)', 'A(3,4)']
>
> Is there a better way to construct a list of such classes?
Note that it's not a list of classes, but a list of instances of A. But
given your specs, nope, your approach is the right one.
> Basically
> what I want is something similar to the following C example:
>
> struct {
> int a;
> int b;
> } bla[]={ {1, 2}, {3, 4} };
Basically (no pun intended[1]), Python is not C. Trying to write C in
Python will only buy you pain and frustration (and this can be
generalized for any combination of two languages for any known
programming language).
[1] well... in fact, yes... !-)
More information about the Python-list
mailing list