【问题标题】:Can you generate instances of a class with unique members using a function?您可以使用函数生成具有唯一成员的类的实例吗?
【发布时间】:2016-05-07 00:10:07
【问题描述】:

我正在尝试生成一个对象的 100 个实例,每个实例都有一个编号的 ID 成员。当我运行它时,我期望它生成 100 个具有 cell_ID 的 Cell 类实例,例如 cell1、cell2、cell3 等。但是,我收到一个属性错误,告诉我 Cell 实例没有 调用强>方法。我真的不知道我想做的事情是否可行,而且我在网上找不到任何关于这个话题的东西。感谢您花时间阅读本文,我真的很感激。

import string
class Cell():
     def __init__(self, x, y, cell_ID):
     self.x = x
     self.y = y
     self.cell_ID = cell_ID
 def __str__(self):
     return "%s:(%i,%i)" % (self.cell_ID, self.x, self.y,)

class Event(Cell):
    def __init__(self):
    print "EVENT TEST"
    self.cell_list = []

def makeCells(self, obj, attr):
    for x in range(0,100):

        obj().attr = attr + str(x)
        self.cell_list.append(obj)


e = Event()
e.makeCells(Cell(0,0, ""), "cell")

【问题讨论】:

  • 除了@TigerhawkT3 “不要那样做”的好建议之外,您实际上还调用了该对象:obj().attr,但这根本行不通。

标签: python


【解决方案1】:

不要不要那样做。使用 list 等数据结构。

import string

class Cell():
     def __init__(self, x, y, cell_ID):
         self.x = x
         self.y = y
         self.cell_ID = cell_ID

     def __str__(self):
         return "%s:(%i,%i)" % (self.cell_ID, self.x, self.y,)

l = [Cell(0, 0, id) for id in range(100)]

【讨论】:

  • 问题是我想为每个实例生成一个唯一的 cell_ID。在单独的函数中执行此操作会更容易吗?顺便谢谢你的帮助,我真的很感激。
  • @Razinmore - 正如您在编辑中看到的那样,使用list 使这变得非常容易。 :)
【解决方案2】:

您正在重复使用同一个 Cell 对象。而是每次都创建一个新的。

因此,不要这样做:

obj().attr = attr + str(x)
self.cell_list.append(obj)

改为这样做:

self.cell_list.append(Cell(0, 0, attr + str(x))

另一个建议是让 Cell 对象获得它自己的递增 ID:

class Cell(object):
    cell_ID = 0

    def __init__(self, x, y):
        Cell.cell_ID += 1
        self.cell_ID = 'cell{}'.format(Cell.cell_ID)
        self.x = x
        self.y = y

    def __str__(self):
        return "%s:(%i,%i)" % (self.cell_ID, self.x, self.y,)

然后你可以调用任意多个,他们都会有一个新的 ID:

l = [Cell(0, 0) for _ in range(100)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2018-02-25
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多