【问题标题】:python class attribute scope - leak to global scope [duplicate]python类属性范围-泄漏到全局范围[重复]
【发布时间】:2017-09-15 03:13:06
【问题描述】:

我对在 python 中为类属性分配参数时看到的一些行为感到非常惊讶。也许有人可以启发我,并帮助我阻止它发生。

基本上,我在类方法中对类属性所做的更改会复制到作为参数传递给类 init 的全局变量中。

是否有内置的方法来阻止这种行为,因为在很多情况下它可能会破坏数据变量以供其他用途。

这是一个基本版本的代码

class BasicClass:

    def __init__(self, data_raw):
        self.data = data_raw
        self.data['new_column'] = 1

# Now outside the class

data = pd.read_csv(...)

data.columns
Out[1]: ['orig_column']

obj = BasicClass(data)

data.columns
Out[2]: ['orig_column','new_column']

【问题讨论】:

  • 试试data_raw.copy()?

标签: python oop scope


【解决方案1】:

这是因为self.datadata 都指向同一个对象。

如果您想要list 的深层副本,那么

def __init__(self, data_raw):
    self.data = data_raw.copy()
    self.data['new_column'] = 1

请参考:How to clone or copy a list?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多