【问题标题】:Is method scope important when defining methods inside a class?在类中定义方法时,方法范围重要吗?
【发布时间】:2019-03-28 23:30:36
【问题描述】:

我有一个方法可以返回四个用于创建矩形的变量。但是该函数使用另一种方法来获取一些值。

所以我的 rectangle_points() 方法分别从 x_value() 和 y_value() 获得两个点,但由于某种原因,我无法从 rectangle_points() 内部对 x_value() 进行函数调用,我得到一个 NameError: name 'x_value'没有定义

from random import *

class Rectangle:
    def x_value():
        return choice(range(0, 800, 10))

    def y_value():
        return choice(range(0, 600, 10))

    def rectangle_points():
        x1 = x_value()
        y1 = y_value()
        x2 = x1 + 10
        y2 = y1 + 10
        return x1, y1, x2, y2

    print('for rectangle points are {}'.format(rectangle_points()))

现在的预期结果应该是打印出四个点,但我得到一个 NameError: name 'x_value' is not defined。 ps 我假设如果要到达那条线,我会为 y1 = y_value() 线遇到同样的问题。

【问题讨论】:

  • 您确实需要熟悉 Python 类的基础知识。 official tutorial is a good place to start
  • 您似乎不小心将代码放入了一个不必要的类中。如果您取消缩进并删除该类,您的代码将运行得更好。
  • Khelwood 提出了一个很好的观点,你没有使用任何内部状态,那你为什么还要上课呢?
  • @juanpa.arrivillaga 类还没有完成,但我正在尝试在 python 中实现生命游戏

标签: python class methods scope nameerror


【解决方案1】:

根据@JBirdVegas 的建议,我想为您提供完整的答案。

from random import choice

class Rectangle:
    def x_value(self):
        return choice(range(0, 800, 10))


    def y_value(self):
        return choice(range(0, 600, 10))


    def rectangle_points(self):
        x1 = self.x_value()
        y1 = self.y_value()
        x2 = x1 + 10
        y2 = y1 + 10
        return x1, y1, x2, y2


r = Rectangle()
print('for rectangle points are {}'.format(r.rectangle_points()))

你必须告诉解释器引用类自己的函数。您可以通过添加self

来实现这一点

这样解释器知道它引用了自己,即Rectangle.x_value,而不仅仅是x_value。正如之前在 cmets 中建议的那样,我建议您查看文档以获取更多详细信息,但这应该可以解决您现在的所有问题。

编辑:我想补充一点,使用 import * 并不总是最好的解决方案,如果库具有相同的命名对象,您可以将其更改为 from random import choice 以避免膨胀和可能的错误

【讨论】:

    【解决方案2】:

    这只是一个快速修复。在为类创建方法时,self 总是在其初始化期间被调用。 然后,这允许您在创建新方法时使用同一类中的其他方法。 这应该可以修复您的代码!

    from random import *
    
    class Rectangle:
        def x_value(self):
            return choice(range(0, 800, 10))
    
        def y_value(self):
            return choice(range(0, 600, 10))
    
        def rectangle_points(self):
            x1 = self.x_value()
            y1 = self.y_value()
            x2 = x1 + 10
            y2 = y1 + 10
            return x1, y1, x2, y2
    rec = Rectangle()
    print('for rectangle points are {}'.format(rec.rectangle_points()))
    

    【讨论】:

      【解决方案3】:

      你好亲啊!!!

      只需添加self 喜欢self.x_value()

      如果第一个参数应该是self

      def x_value(self):

      self 表示该函数是实例成员而不是类成员。

      print 可能不应该缩进,但这并不重要

      【讨论】:

      • 也许尝试阐明一个更丰富的答案?我的意思是它是正确的,但简短且无法解释?
      • 哈哈,你的权利没有看到它们是功能......更新......不想只是给出答案,但你的权利我解释得太短了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 2020-04-22
      • 2012-05-13
      • 2012-05-11
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      相关资源
      最近更新 更多