【问题标题】:Python class not recognizing listPython类不识别列表
【发布时间】:2020-05-23 14:34:49
【问题描述】:

我正在尝试构建我的第一个类,在检查了一些文档和其他 StackOverflow 问题之后,我无法弄清楚为什么我在下面列出的代码中得到 NameError: name 'executed_trades' is not defined

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

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

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

【问题讨论】:

    标签: python list class


    【解决方案1】:

    当您引用executed_trades 时,您在add_position 方法中缺少self

    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)
    

    【讨论】:

    • 非常感谢。事后看来,其中一件很简单的事情。欣赏它。
    【解决方案2】:

    要访问executed_trades,请使用self.executed_trades,因为它是您的类的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      相关资源
      最近更新 更多