Skip to main content
 首页 » 编程设计

Python 对象作为字典列表的列表

2025年01月19日13exmyth

我正在尝试开发一个行为类似于列表列表的类。我需要它在 deap 框架中将其作为个人类型传递。目前,我正在使用 numpy 对象数组。这是代码。

import numpy 
 
class MyArray(numpy.ndarray): 
    def __init__(self, dim): 
        numpy.ndarray.__init__(dim, dtype=object) 

但是当我尝试将值传递给 MyArray 的对象时,

a = MyArray((2, 2)) 
a[0][0] = {'procID': 5} 

我得到一个错误,

Traceback (most recent call last): 
File "D:/PythonProjects/NSGA/src/test.py", line 23, in <module> 
    'procID': 5 
TypeError: float() argument must be a string or a number, not 'dict' 

欢迎提出任何建议。您也可以在不使用 numpy 的情况下向我展示一种不同的方式,这有助于创建类型。

可以找到类似的问题here

请您参考如下方法:

根据 the documentation ,看起来 ndarray 使用 __new__() 来进行初始化,而不是 __init__()。特别是,数组的 dtype 在 __init__() 方法运行之前就已经设置好了,这是有道理的,因为 ndarray 需要知道它是什么dtype 就是知道要分配多少内存。 (内存分配与 __new__() 关联,而不是 __init__()。)因此您需要覆盖 __new__() 以提供dtype 参数到 ndarray。

class MyArray(numpy.ndarray): 
    def __new__(cls, dim): 
        return numpy.ndarray.__new__(cls, dim, dtype=object) 

当然,您也可以在类中使用__init__() 方法。它将在 __new__() 完成后运行,这将是设置其他属性或您可能想要执行的任何其他操作的适当位置,而不必修改 的行为ndarray 构造函数。

顺便说一下,如果你子类化 ndarray 的唯一原因是你可以将 dtype=object 传递给构造函数,我只会使用工厂函数.但我假设您的真实代码中还有更多内容。