-1

Trying out the 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

Using this as a test example:

XYPoint.__add__(32,34)

When running the code, I am getting the error: AttributeError: 'int' object has no attribute 'x' Tried adding return to the def; same error.

smci
  • 32,567
  • 20
  • 113
  • 146
tbc
  • 49
  • 1
  • 6

1 Answers1

3

Your example doesn't try to add two instances of XYPoint, rather it just tries to use __add__ method of XYPoint, which excepts a first argument of self in this case XYPoint not 32 which is an int. In the __add__ function it tries to do something like

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

which is as you may guess is an error.

Perhaps this may be what you are trying to do instead.

>>> @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)
>>>
Işık Kaplan
  • 2,815
  • 2
  • 13
  • 28