无法在 cython 中使用该类列表中的类的属性

问题描述

为什么我不能调用类的属性,如果我从相同对象的数组中调用它?例如,我有一个 Point 类,想创建一个 n 这样的 Points 数组:arr = [Point() for i in range(n)]。然后我想取这些点中的一个 x 和一个 y。我写print(arr[<index>].x,arr[<index>].y)。如果我在 python 中这样做,它会起作用,但是当我尝试使用 cython 时,即使没有定义类型,它也会说,我在 Point 类中没有属性 x。但是,如果我不使用数组而只创建单个对象 point = Point(),那么当我编写 print(point.x,point.y 时程序运行良好。 这是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()

输出:

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

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 debug():
    debug_arr = list([Point(i,debug_arr[0].y)

def main():
    debug()

输出:

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].y)
AttributeError: 'main.Point' object has no attribute 'x'

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)