Python类无法识别列表

我正在尝试建立我的第一个类,在检查了一些文档和其他StackOverflow问题之后,我无法弄清楚为什么在下面列出的代码中出现“ NameError:未定义名称'executed_trades'”的原因:

class Position:
    def __init__(self):
        self.executed_trades = []

    def add_position(self, execution):
        if execution not in executed_trades:
            executed_trades.append(execution)

它不属于__init __()吗?我缺少的类中的声明有什么不同吗?感觉像是一个相对简单的错误,但我似乎无法弄清楚。

评论
自述
自述

In order to access executed_trades, use self.executed_trades as it's an attribute of your class.

点赞
评论
Dicke
Dicke

You are missing self in add_position method when you refer to executed_trades:

class Position:
    def __init__(self):
        self.executed_trades = []

    def add_position(self, execution):
        if execution not in self.executed_trades:
            self.executed_trades.append(execution)
点赞
评论