我是新手。我有一个Triangle类,它接收3个格式为[x,y]的列表变量:a
,b
和c
。如何返回带有三角形笛卡尔点的字符串?
class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c
def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
return ""
答案 0 :(得分:0)
这是我的实现以及如何实现。您可以返回字符串,并记住将整数转换为字符串。
class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c
def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
return "Point A: " + str(self.a[0]) + " " + str(self.a[1]) + "\nPoint B: " + str(self.b[0]) + " " + str(self.b[1]) + "\nPoint C: " + str(self.c[0]) + " " + str(self.c[1])
t = Triangle([5,4], [1,2], [7,9])
print(t)
输出:
Point A: 5 4
Point B: 1 2
Point C: 7 9
答案 1 :(得分:0)
假设一个点是一个像(1.5,6.7)之类的元组
代码如下:
class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c
def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
return f"Point A: {self.a[0]} {self.a[1]}\nPoint B: {self.b[0]} {self.b[1]}\nPoint C: {self.c[0]} {self.c[1]}"
您可以使用以下方法进行检查:
t = Triangle((2.34,4.62), (6.7,8.52), (9.34,3.32))
print(t)
答案 2 :(得分:0)
我建议添加一个新方法,该方法返回三角形的单个点的表示形式。这样,您可以在__str__
方法中使用它,并且代码将更少冗余和更简洁。
class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c
def point_repr(self, p):
"""
Make a string representation of a point 'p', and return it.
p: list of the form [x, y].
"""
coords = "{0} {1}".format(*p)
# OR
coords = "{} {}".format(p[0], p[1])
return coords
def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
template = "Point {}: {}"
a = self.point_repr(self.a)
b = self.point_repr(self.b)
c = self.point_repr(self.c)
point_a = template.format("A", a)
point_b = template.format("B", b)
point_c = template.format("C", c)
formatted = "{}\n{}\n{}".format(point_a, point_b, point_c)
return formatted