使用Dataclass并获取AttributeError:'int'对象没有属性'x'

时间:2019-04-28 20:47:45

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

尝试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'对象没有属性'x' 尝试增加def的收益;同样的错误。

1 个答案:

答案 0 :(得分:1)

您的示例没有尝试添加两个XYPoint实例,而是尝试使用__add__的{​​{1}}方法,但第一个参数XYPoint除外。在这种情况下,self不是XYPoint,这是一个整数。在32函数中,它尝试执行

之类的操作
__add__

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

也许这可能是您正在尝试做的。

new = XYPoint(32.x, 32.y)