'How to create a python class contains empty list, add points to it, and return cordinates of points as tuple
I need some help in python oop, I want to create an empty list as an instance in a python class, then add a method that appends points in that empty list, and add a string method that returns the coordinates of all points, like ( x1,y1) (x2,y2) (x3,y3 ) . . . (xn,yn ) here is my code but it's not working:
class Foo:
# This list is initially empty
def __init__(self, lst):
self.lst = []
# append_point method which takes a point as an argument and
# adds points to the instance variable.
def append_point(self, **point):
self.lst.append(point)
return tuple(self.lst)
# returns the coordinates of all points
def __str__(self):
return f'cordinates : {self.lst}'
if __name__ == '__main__':
cor = Foo([1,2,4,3,5,7])
print(cor)
Solution 1:[1]
class Points:
def __init__(self, points=None):
if points is None:
points = []
self.points = points
def add_point(self, point):
self.points.append(point)
def __str__(self):
return f'Points coordinates: {self.points}'
points = Points([(0,0),(0,1)])
points.add_point((1,1))
print(points)
Output:
Points coordinates: [(0, 0), (0, 1), (1, 1)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chepner |
