【问题标题】:scope in class pythonpython类中的作用域
【发布时间】:2017-08-07 19:31:34
【问题描述】:

我有一堂课:

class Difference:
    def __init__(self,a1):
      self.a1=a1
    def  computeDifference(self):
      d0=max([max(self.a1)-i for i in self.a1])
      return d0
      maximumDifference=d0

现在当我尝试像下面这样访问类时出现以下错误:

_ = input().strip()
a = [int(e) for e in input().strip().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)

错误:

Traceback(最近一次调用最后一次): 文件“q.py”,第 2 行,在 类差异: 文件“q.py”,第 8 行,差异 最大差=d0 NameError: name 'd0' is not defined

出了什么问题?

【问题讨论】:

  • 您从未告诉 pytho d0 是什么,当您尝试将 maximumDifference 设置为 d0 时,python 会抛出错误。在你的类Difference 中定义d0 以避免错误

标签: python python-3.x class


【解决方案1】:

一些事情:

  1. 您需要先定义d0 是什么,然后才能将其分配给maximumDifference
  2. 即使您确实定义了d0 并尝试将其分配给maximumDifference,也无法到达,因为该行位于return 声明之后。
  3. 不正确的缩进,但这可能正是您发布问题的方式。我编辑了您的问题以修复缩进错误

您可以这样做来解决上述问题:

def  computeDifference(self):
        d0=max([max(self.a1)-i for i in self.a1])
        self.maximumDifference=d0
        return d0

上面的代码可以工作,但是在 __init__ 之外定义属性不是好的做法最好在 __init__ 中定义类属性

class Difference:

    def __init__(self,a1):
      self.a1=a1
      self.maximumDifference = self.computeDifference()
    def  computeDifference(self):
        d0=max([max(self.a1)-i for i in self.a1])
        return d0

【讨论】:

    【解决方案2】:

    你的问题是缩进。 Python 代码必须缩进良好才能正常工作。试试:

    class Difference:
    
        def __init__(self,a1):
          self.a1=a1
    
        def  computeDifference(self):
            d0=max([max(self.a1)-i for i in self.a1])
            self.maximumDifference=d0
            return d0
    

    另外,maximumDifference=d0 行将永远不会到达,因为它是在返回之后放置的,即使是这样,您的代码也无法工作,因为您只在本地使用。要在该函数之外存储和使用maximumDifference,您应该将其存储在self.maximumDifference 中,如上例所示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 2015-03-02
      • 2013-02-09
      相关资源
      最近更新 更多