我有一个存储简单数据的简单类。课程如下。
protocol MyProtocol
{
var prop: BaseClass
}
struct MyImplementation: MyProtocol
{
var prop: SubClass
}
class BaseClass {}
class SubClass: BaseClass {}
class DifferentSubClass: BaseClass {}
var instance: MyProtocol = MyImplementation()
instance.prop = DifferentSubClass()
// Should be legal because the protocol says so but the type of prop in instance is SubClass.
调用此类的代码是
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.N
非常感谢!而且我知道我的帖子很混乱,我不知道如何让它更“漂亮”
答案 0 :(得分:3)
所以,看起来你在循环中分配实际的类(而不是类的实例)。你这样做的地方:
ObjectList[ObjectListCounter] = DataFormater
我认为你真正想要的是这个
ObjectList[ObjectListCounter] = DataFormater(...insert args here....)
编辑以解决评论:
您的类init方法如下所示:
def __init__(self, N, P, K, price):
这意味着要创建类的实例,它将如下所示:
my_formater = DataFormater(1, 2, 3, 4)
然后,您就可以访问my_formater.N
,其值为1
。
您尝试执行的操作是访问CLASS级别属性DataFormater.N
。这通常用于您具有在类的实例之间不会更改的常量变量的情况。例如:
class DataFormater():
CONSTANT_THING = 'my thing that is always the same for every instance'
然后,您就可以直接从类中访问该变量,如下所示:
DataFormater.CONSTANT_THING
我希望能够解决问题。