【问题标题】:Modify a member variable outside the class object and have changes in the class object修改类对象外的成员变量,并在类对象中有变化
【发布时间】:2016-02-25 10:45:18
【问题描述】:

我在 python 中有一个类:

class A:
  def __init__(self):
    self.obj = None
  def setObj(self, npArray):
    self.obj = npArray
  def getObj(self):
    return self.obj

在另一个 python 脚本中,我实例化了一个类 A 的对象并设置“obj”,然后在其他地方获取它

objOfA.setObj(npArray)

''' Some operations '''

objOut = objOfA.getObj()

''' More operations '''
np.append(objOut,[0.25])  ## Here np.append is used just as an example. There can be many other algebraic operations. 

''' operations using objOfA '''

在上面使用objOfA的操作中,我想查看修改后的数组(附加0.25)。

在 C++ 中,使用指针或引用是很有可能的。但是我在 python 中很难做到这一点。我了解 python 如何以及何时使用对对象的引用。我的问题是尽快

objOut = objOfA.getObj()

我得到了数组的副本,但没有得到objOut 的引用。

有没有办法可以做到这一点。

提前谢谢你。

【问题讨论】:

    标签: arrays python-3.x object numpy reference


    【解决方案1】:

    根据文档,np.append 返回一个新数组(重点是我的):

    arr 的副本,其中 values 附加到 axis注意追加不会就地发生:分配并填充一个新数组。如果 axis 为 None,out 是一个扁平数组。

    因此您必须将返回值分配回您的对象:

    objOut.setObj(np.append(objOut.getObj(), [0.25]))
    

    请注意,不鼓励在 Python 中使用 getter 和 setter 方法,您应该直接访问对象:

    objOut.obj = np.append(objOut.obj, [0.25])
    

    如果你不依赖 numpy 数组,你可以只使用可变的列表:

    objOut.obj = [1, 2, 3]
    objOut.obj.append(0.25)
    objOut.obj.extend([4, 5, 6])
    

    【讨论】:

    • 感谢您的回答...我以 np.append 作为操作示例。可以有其他数学运算。还有关于 getter 和 setter 函数。是的我同意。还有一些实例,其中 obj 通过类对象的层次结构传递。在那些情况下它也能工作吗?另外是的,我依赖于 numpy 数组。
    • 一般避免使用x=fun(x)x=x-...等表达式;使用 x-=...、x[:]=.... Also learn the difference between views and copies. And you cannot grow an array inplace. Test things like id(x)` 和 x.__aray_interface__
    • 是的,不管是objOut.obj 还是objOut.obj.and.more.hierachies.obj。这真的取决于操作。改变 numpy 数组维度的东西通常不会就地修改数组,而对 numpy 数组的数学运算可以就地执行(使用分配运算符,如 +=*=)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多