我正在尝试制作一个像这样工作的点元组:
p1 = (3, 5)
p1.x
# returns 3
p1.y
# returns 5
p1
# returns (3, 5)
p1.x = 7
# mutable
所以我可以调用
p1[0]
而不是 p1.x
,同时调用 p1
返回元组,而不是对象。
我想在 Pygame 中使用这个数据结构。我试着像这样使用
recordclass
库:
Point = recordclass('Point', 'x y')
start_point = Point(0, 0)
pygame.draw.circle(screen, (0, 0, 0), start_point, 5)
我得到的错误是:
Traceback (most recent call last): File
"D:\Repos\PyCharm\Sailboat\main.py", line 85, in <module>
pygame.draw.circle(screen, (0, 0, 0), start_point, 5)
TypeError: center argument must be a pair of numbers
types.SimpleNamespace
:
>>> from types import SimpleNamespace
>>> p = SimpleNamespace(x=3, y=5)
>>> p.x
3
>>> p.y
5
>>> p.x = 7
>>> p
namespace(x=7, y=5)
解决方法:
Point = recordclass('Point', 'x y')
start_point = Point(0, 0)
#...
# changing to another Point using a tuple
start_point = Point(*some_tuple)
#...
pygame.draw.circle(screen, (0, 0, 0), start_point, 5)
# works fine
事实证明,
start_point = Point(some_tuple)
行是真正的问题,图书馆没有正确分配它,也没有告诉它不应该那样做。将其更改为start_point = Point(some_tuple[0], some_tuple[1])
解决了这个问题。
只需创建一个名为
Tuple
的自定义类,如下所示:
class Tuple:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
p1 = Tuple(3, 5)
print(p1.x)
print(p1.y)
print(p1)
p1.x = 7
print(p1)
输出将是:
3
5
(3, 5)
(7, 5)