简体   繁体   English

Python创建类的多个实例

[英]Python Creating Multiple Instances of a Class

I'm trying to create a NumPy array of objects as follows... 我正在尝试创建一个NumPy对象数组,如下所示......

import numpy as np

class Pixel:
    def __init__(self):
        self.r = 0
        self.g = 0
        self.b = 0

class Image:
    def __init__(self):
        self.pixels = np.full((4, 4), Pixel())

if __name__ == '__main__':
    image = Image()
    print(image.pixels)

The output being... 输出是......

[[<__main__.Pixel object at 0x02A92F70>
  <__main__.Pixel object at 0x02A92F70>]
 [<__main__.Pixel object at 0x02A92F70>
  <__main__.Pixel object at 0x02A92F70>]]

which appears to have created an array of the same object. 它似乎创建了同一个对象的数组。 My question is how to initialise the array with a different object for each pixel? 我的问题是如何使用每个像素的不同对象初始化数组?

Kind regards 亲切的问候

You can use np.array function and initialize it from standard python list as following: 您可以使用np.array函数并从标准python列表初始化它,如下所示:

class Image:
def __init__(self):
    self.pixels = np.array([Pixel() for i in range(2 * 2)]).reshape([2, 2])

The result is as following: 结果如下:

[[<__main__.Pixel object at 0x00000218B89F6438>
  <__main__.Pixel object at 0x00000218B89F64A8>]
 [<__main__.Pixel object at 0x00000218B89F4D68>
  <__main__.Pixel object at 0x00000218B89F43C8>]]

As you see they are not the same object. 如你所见,它们不是同一个对象。

Note that it will not hart your time complexity since in any case you need to initialize O(n) objects. 请注意,它不会影响您的时间复杂度,因为在任何情况下您都需要初始化O(n)对象。

Thanks for all of the replies, most helpful. 感谢所有的回复,最有帮助。 The method I have found that works best for my particular case is to use the numpy.empty() method to create an array of the correct size and then iterate through the elements filling the array with new objects. 我发现最适合我的特定情况的方法是使用numpy.empty()方法创建一个正确大小的数组,然后遍历用新对象填充数组的元素。 It might not be the most efficient but it is the most readable to me. 它可能不是最有效的,但它对我来说最具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM