【问题标题】:Using Dataclass and getting AttributeError: 'int' object has no attribute 'x' [duplicate]使用 Dataclass 并获取 AttributeError:“int”对象没有属性“x”[重复]
【发布时间】:2019-09-17 13:14:37
【问题描述】:

试用code from

from dataclasses import dataclass, field, InitVar

@dataclass
class XYPoint:
    last_serial_no = 0
    x: float
    y: float = 0
    skip: InitVar[int] = 1
    serial_no: int = field(init=False)

    def __post_init__(self, skip):
        self.serial_no = self.last_serial_no + self.skip
        self.__class__.last_serial_no = self.serial_no

    def __add__(self, other):
        new = XYPoint(self.x, self. y)
        new.x += other.x
        new.y += other.y

以此作为测试示例:

XYPoint.__add__(32,34)

运行代码时,出现错误:AttributeError: 'int' object has no attribute 'x' 尝试将 return 添加到 def;同样的错误。

【问题讨论】:

标签: python python-3.x python-dataclasses


【解决方案1】:

您的示例没有尝试添加两个XYPoint 实例,而是尝试使用XYPoint__add__ 方法,除了self 的第一个参数在这种情况下XYPoint 不是@ 987654326@ 这是一个整数。在__add__ 函数中,它尝试执行类似

的操作
new = XYPoint(32.x, 32.y)

您可能会猜到这是一个错误。

也许这可能是您想要做的。

>>> @dataclass
... class XYPoint:
...     x: float
...     y: float
...     def __add__(self, other):
...         cls = self.__class__
...         return cls(self.x+other.x, self.y+other.y)
...
>>> XYPoint(2,3) + XYPoint(5,7)
XYPoint(x=7, y=10)
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 2021-11-30
    • 2020-03-26
    • 2013-04-15
    • 2021-01-18
    • 2019-05-30
    • 2021-02-24
    • 2021-08-01
    相关资源
    最近更新 更多