【问题标题】:Object-oriented instance variable issue面向对象的实例变量问题
【发布时间】: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.prices2.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


    【解决方案1】:

    您将同一列表的引用传递给两个实例。列表是一个可变对象,因此它是按引用传递的。

    一种解决方案是创建两个列表:

    def test():
        l_1 = []
        l_2 = []
        s1= Stock('A', l_1)
        s2= Stock('B', l_2)
        n=0   
    
        while n < 390:
            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 #
    

    但是,您还将在类外部附加到 l_1 和 l_2,因为它们共享相同的引用。 由于 d1 和 d2 是价格列表,另一种解决方案是在实例化时创建一个列表,如果 Add_Price() 传递一个列表,则扩展 Stock 的列表,如果不是列表,则附加一个价格。

    股票类构造函数:

    class Stock(object):
    
        def __init__(self,name,prices=None):
            self.name = name
            self.price = prices or [] #create a new list on instantiation
    
        def Add_Price(self,data):
            if isinstance(data, list):
                self.prices.extend(data)
            else:
                self.prices.append(data)
    

    然后在你的 test() 函数中:

    def test():
        s1 = Stock('A')
        s2 = Stock('B')
    
        s1.Add_Price(d1[:390])
        s2.Add_Price(d2[:390])
    

    d1[:390] 是拼接的,它表示从索引 0(包括)到索引 390(不包括)的所有元素,这样您就可以消除对 while 循环的需要。

    【讨论】:

    • 谢谢,我可能应该提到循环存在其他原因......但答案的第一部分解决了问题
    • @abcla 我编辑了我的帖子。如果您没有在 while 循环中的其他任何地方使用特定的 n 元素,您仍然可以使用拼接的性能优势,但是是的,如果您在其他地方使用该元素,您可能希望根据您的情况单独附加。另外,如果这是正确的答案,请采纳:)
    猜你喜欢
    • 2012-05-18
    • 1970-01-01
    • 2014-12-22
    • 2012-04-04
    • 2016-09-25
    • 2015-10-12
    • 2011-06-18
    • 2014-07-10
    • 1970-01-01
    相关资源
    最近更新 更多