【发布时间】:2017-01-18 02:06:23
【问题描述】:
我有以下代码:
class Stock(object):
def __init__(self,name,price):
self.name = name
self.price = price
def Add_Price(self,data):
self.price.append(data)
def test():
l=[]
n=0
while n < 390:
s1= Stock('A', l)
s2= Stock('B', l)
s1.Add_Price(d1[n]) # d1 is a list with the prices for A #
s2.Add_Price(d2[n]) # d2 is a list with the prices for B #
print s1.price, s2.price
n=n+1
当我运行它时,我会假设调用s1.price 你会收到一个带有股票价格A 的数组,而s2.price 将有一个股票价格B。但是,当我运行它时,s1.price 和 s2.price 是相同的。
所以似乎当我将一个新值附加到self.price 时,它并没有将它附加到该类的当前实例的变量中。
谁能指出我做错了什么?
编辑:
当前输出:
[10 150] [10 150]
[10 150 10.2 150.3] [10 150 10.2 150.3]
期望的输出:
[10] [150]
[10 10.3] [ 150 150.3]
【问题讨论】:
标签: python class oop object instance