Defining multiple objects of the same class in python
is there any short开发者_开发百科hand 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?
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.
Not really.
p1, p2, p3 = [Point() for x in range(3)]
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)]
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))
精彩评论