【问题标题】:Object initialization in Python [duplicate]Python中的对象初始化[重复]
【发布时间】:2017-10-06 11:46:14
【问题描述】:

我创建了一个简单的类,其中的对象具有初始值 x0。当我改变另一个值 x 时,我的 x0 也在改变。

我认为 x0 应该保持不变。你能解释一下为什么会这样吗?

文件 main.py:

import numpy as np
from simpleclass import test


def main():

    params = dict()
    params['position'] = np.array([1.0, 2.0])

    object = test(params)

    print(object.x0)
    print(object.x)

    object.run(2)

    print(object.x0)
    print(object.x)


if __name__ == "__main__":
    main()

文件simpleclass.py:

class test():

    def __init__(self, params):
        self.x0 = params['position']
        self.x = self.x0

    def run(self, num):
        self.x += self.x*num

结果:

[ 1.  2.]
[ 1.  2.]
[ 3.  6.]
[ 3.  6.]

【问题讨论】:

    标签: python class object initialization


    【解决方案1】:

    问题出在

    class test():
        def __init__(self, params):
            self.x0 = params['position']
            self.x = self.x0
    
        def run(self, num):
            self.x += self.x*num
    

    self.x = self.x0 这里 self.x 和 self.x0 指向同一个对象。你可以复制self.x0。

    import copy
    
    class test():
        def __init__(self, params):
            self.x0 = params['position']
            self.x = copy.deepcopy(self.x0)
    
        def run(self, num):
            self.x += self.x*num
    

    【讨论】:

      【解决方案2】:

      surya singh 是对的,只要打印内存地址,就会得到相同的数字

      class test():
          def __init__(self, params):
              self.x0 = params['position']
              self.x = self.x0
              print id(self.x)
              print id(self.x0)
      

      【讨论】:

      • 谢谢!我会记住这一点
      【解决方案3】:

      你只是传递一个参考

      self.x = self.x0,您只是传递了一个引用。对于self.x += self.x*num,引用也没有改变。所以在这两个操作之后,xx0 仍然指向同一个数组。

      如果你使用不可变的对象会有所不同,例如 tuple

      params['position'] = (1, 2)
      

      使用 tuple+= 做的事情与你想要的不同,但是你看,xx0 指向不同的对象。

      (1, 2)
      (1, 2)
      (1, 2)
      (1, 2, 1, 2, 1, 2)
      

      使用副本

      您想创建数组的副本,numpy 有一个 built-in method 用于此

      self.x = self.x0.copy()
      

      结果:

      [ 1.  2.]
      [ 1.  2.]
      [ 1.  2.]
      [ 3.  6.]
      

      【讨论】:

        猜你喜欢
        • 2012-01-17
        • 2013-08-28
        • 2015-12-03
        • 1970-01-01
        • 2016-02-26
        • 2013-02-08
        • 2013-07-23
        • 1970-01-01
        • 2021-08-25
        相关资源
        最近更新 更多