Reputation: 2048
is there any shorthand method of defining multiple objects of the same class in one line. (I'm not talking about lists or array of objects)..
i mean something like
p1,p2,p3 = Point()
any suggestions?
Upvotes: 1
Views: 829
Reputation: 29131
Think map is also acceptable here:
p1, p2, p3 = map(lambda x: Point(), xrange(3))
But generator expression seems to be a bit faster:
p1, p2, p3 = (Point() for x in xrange(3))
Upvotes: 1
Reputation: 21089
It may be slightly more efficient to use a generator comprehension rather than a list comprehension:
p1, p2, p3 = (Point() for _ in range(3)) # use xrange() in versions of Python where range() does not return an iterator for more efficiency
There's also the simple solution of
p1, p2, p3 = Point(), Point(), Point()
Which takes advantage of implicit tuple packing and unpacking.
Upvotes: 6
Reputation: 7780
What exactly are you trying to achieve?
This code does what you're asking, but I don't know if this is your final goal:
p1, p2, p3 = [Point() for _ in range(3)]
Upvotes: 2
Reputation: 799500
Not really.
p1, p2, p3 = [Point() for x in range(3)]
Upvotes: 3