我有一个存储简单数据的简单类。该类如下。

class DataFormater:

    def __init__(self, N, P, K, price):

       self.N = N
       self.P = P
       self.K = K
       self.price = price


调用此类的代码是

from DataFormater import DataFormater

#global variables
ObjectList = [0,1,2,3,4,5,6,7,8,9,10,
              11,12,13,14,15,16,17,18,19,20,
              21,22,23,24,25,26,27,28,29,30,
              31,32,33,34,35,36,37,38,39,40,
              41,42,43,44,45,46,47,48,49,50]
ObjectListCounter = 0

# main
print "enter you N-P-K values, followed by a coma, then the price"
print "example ---->  5 5 5 %50 "
print "return as many values as you want to sort, then enter, 'done!' when done."

while True:
    RawData = raw_input()
    if RawData == 'done!':
        break

    else:

        ObjectList[ObjectListCounter] = DataFormater
        ObjectList[ObjectListCounter].N = int(RawData[0])
        # very simple test way of putting first indice in ObjectList[ObjectListCounter].N
        ObjectListCounter += 1

print ObjectList[0].N
print ObjectList[1].N


我的想法是ObjectList[0]将创建对象“ 1”,我可以用1.N调用该对象

但是,当我调用这些时,似乎已经覆盖了先前的实例。

这是打印的...

return as many values as you want to sort, then enter, 'done!' when done.
12
1
done!
1
1


非常感谢!而且我知道我的帖子太乱了,我不知道该如何使其更“漂亮”

最佳答案

因此,看起来您正在循环中分配实际的类(而不是类的实例)。在哪里执行此操作:

ObjectList[ObjectListCounter] = DataFormater


我想你真正想要的是

ObjectList[ObjectListCounter] = DataFormater(...insert args here....)


编辑以解决评论:

您的类初始化方法如下所示:

def __init__(self, N, P, K, price):


这意味着要创建您的类的实例,将如下所示:

my_formater = DataFormater(1, 2, 3, 4)


然后,您将能够访问值为my_formater.N1

相反,您要尝试的是访问CLASS级别属性DataFormater.N。通常在常量变量在类实例之间不变的情况下使用。例如:

class DataFormater():

    CONSTANT_THING = 'my thing that is always the same for every instance'


然后,您将可以直接从类中访问该变量,如下所示:

DataFormater.CONSTANT_THING


我希望这可以解决问题。

关于python - 类对象的动态实例互相覆盖,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45618561/

10-16 18:45