Why can't I call an attribute of a class, if I call it from an array of same Objects? For example, I have a class Point and want to create an array of n
such Points: arr = [Point() for i in range(n)]
. Then I want to take an x
and a y
of these points. I write print(arr[<index>].x, arr[<index>].y)
. If I do that in python it works but when I try the same with cython, even without defining types, it says, that I don't have an attribute x
in the class Point. However, if I don't use an array and just create a single object point = Point()
, then the program works just fine when I write print(point.x, point.y
.
Here is code in python:
class Point():
def __init__(self, x = 0., y = 0.0):
self.x = x
self.y = y
# print(self.x, self.y)
def __str__(self):
return f'{self.x}, {self.y}'
def debug():
debug_arr = list([Point(i, i + 1) for i in range(1)])
debug_point = Point(1, 2)
print('debug_point by hand:', debug_point.x, debug_point.y)
print('debug_point with __str__ function:', debug_point)
print('debug_arr:', debug_arr)
print('debug by taking index and argument:', debug_arr[0].x, debug_arr[0].y)
debug()
Output:
debug_point by hand: 1 2
debug_point with __str__ function: 1, 2
debug_arr: [<__main__.Point object at 0x000002B79F025FD0>]
debug by taking index and argument: 0 1
The same code in cython:
cdef class Point():
cdef double x, y
def __init__(self, x: double = 0., y: double = 0.0):
self.x = x
self.y = y
# print(self.x, self.y)
def __str__(self):
return f'{self.x}, {self.y}'
def debug():
debug_arr = list([Point(i, i + 1) for i in range(1)])
debug_point = Point(1, 2)
print('debug_point by hand:', debug_point.x, debug_point.y)
print('debug_point with __str__ function:', debug_point)
print('debug_arr:', debug_arr)
print('debug by taking index and argument:', debug_arr[0].x, debug_arr[0].y)
def main():
debug()
Output:
debug_point by hand: 1.0 2.0
debug_point with __str__ function: 1.0, 2.0
debug_arr: [<main.Point object at 0x0000025AF0C45C00>]
Traceback (most recent call last):
File "C:\*******\Program.py", line 2, in <module>
main.main()
File "main.pyx", line 131, in main.main
debug()
File "main.pyx", line 128, in main.debug
print('debug by taking index and argument:', debug_arr[0].x, debug_arr[0].y)
AttributeError: 'main.Point' object has no attribute 'x'