I believe there is no initializer list-like where you just need to pass in the constant value to the constructor as parameters.. Let say I have a class "Point" which has x,y,z to be passed in the Point to constructor..it is fine.. But then if I make a class "Triangle" I want to take three "Points" with it When defining Triangle object I have difficulty passing in the parameters like in c++ using the initializer list with the '{' '}' and pass in the constant/literal accordingly..but there are no options like this in python.. I need to give the name first to all the points before I can pass it to the triangle constructor.. Is there any way I can do this? I tried using the *args by python but it seems it can only used for one tuple not more than that..I requested three tuples but it says it cannot do it.. I guess I want to write code back in c++
You can indeed do this with *args. class Point: def__init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return f"Point({self.x}, {self.y}, {self.z})" class Triangle: def __init__(self, *points): if len(points) != 3: raise ValueError() self.points = points t = Triangle( *[Point(1, 2, 3), Point(4, 5, 6), Point(7, 8, 9)] ) for point in t.points: print(point)
You can do the same with named attributes by using **kwargs instead of *args. But the important thing here is that this requires the __init__ to accept the arguments, which is not quite the same as initializer lists, which allow arbitrary assignment of attributes, regardless of constructor signature. There are succint ways if doing arbitrary names assignments in python also, but still not exactly like initializer lists.