【发布时间】:2021-12-25 23:35:46
【问题描述】:
我一直遇到数据类的问题,尽管使用了装饰器并将参数传递给数据类,但我会得到一个TypeError,说明该对象不接受任何参数。这似乎很喜怒无常,似乎不是由代码更改触发的,对同事有用的东西对我不起作用(但有时会)。我们都使用 Python 3.9.7,并且都使用 PyCharm 编写代码。
我从 Windows 切换到 Ubuntu 试图阻止这个问题,但大约一周后,它再次发生。这是我最后一个堆栈跟踪错误:
Traceback (most recent call last):
File "/home/pedro/Documents/datacollect/Python-Shape-Game/main.py", line 188, in <module>
shapes = load_shapes()
File "/home/pedro/Documents/datacollect/Python-Shape-Game/main.py", line 139, in load_shapes
return [factory.create(item) for item in data["shapes"]]
File "/home/pedro/Documents/datacollect/Python-Shape-Game/main.py", line 139, in <listcomp>
return [factory.create(item) for item in data["shapes"]]
File "/home/pedro/Documents/datacollect/Python-Shape-Game/factory.py", line 28, in create
return creation_function(**arguments)
TypeError: Rectangle() takes no arguments
pygame 2.1.0 (SDL 2.0.16, Python 3.9.7)
它使用工厂/插件模式从 JSON 中注册形状,factory.py 中最值得注意的行是:
shape_creation_functions: dict[str, Callable[..., Shape]] = {}
# ...
creation_function = shape_creation_functions[shape_type]
return creation_function(**arguments)
这是失败的对象:
class Shape(Protocol):
"""Represents a shape"""
type: str
rgb: list
colour: tuple
method: str
positions: dict
radius: int
def map(self, position: str) -> Union[list[tuple[Any, Any]], tuple]:
"""Map the shape to the screen"""
@dataclass()
class Rectangle(Shape):
"""Represents a rectangle"""
type: str
rgb: list
colour: tuple
method: str
positions: dict
def map(self, position: str) -> Union[list[tuple[Any, Any]], tuple]:
"""Draw the shape on the screen"""
rect = (
self.positions[position][0],
self.positions[position][1],
self.positions[position][2],
self.positions[position][3]
)
return rect
【问题讨论】:
-
请分享
Shape代码和试图创建Rectangle的代码 -
一般来说 - 你在这里尝试做什么?从 dict 创建一个数据类?
-
请将代码添加到帖子中 - 不要作为评论。
-
在我们继续之前 - 你能解释一下当前的继承吗?为什么我们在基类和矩形中都找到相同的属性?
-
@HelloSpeakman:是的,我现在明白了。谢谢,抱歉打扰了。
标签: python ubuntu-20.04 python-3.9