【问题标题】:invalid syntax when using self.size = size使用 self.size = size 时语法无效
【发布时间】:2013-02-26 11:32:39
【问题描述】:

超级,对 Python 和一般编程来说超级新。我有一个应该很简单的问题。我正在使用 Python 3.1 版的 Python 初学者编程书。

我目前正在编写书中的一个程序,并且正在了解使用 python 时缩进的重要性,因此我正在修复我发现的那些错误,然后我到达了我放置 self.size = size 的位置,它强调了这一点代码块中的self无效语法,但我是从手册中逐字输入这个单词,所以我不确定我做错了什么。这是代码块:

def _init_(self, x, y, size):
    """ Initialize asteroid sprite. """
    super(Asteroid, self)._init_(
    image = Asteroid.images[size],
    x = x, y = y,
    dx = random.choice([1, -1]) * Asteroid.SPEED * random.random()/size,
    dy = random.choice([1, -1]) * Asteroid.SPEED * random.random()/size

    self.size = size 

问题是最后一行,它将 self 突出显示为无效语法,但没有其他内容...最后要注意的是,当我将此特定块放入 shell 并尝试在那里运行它时,它也会给我一个语法错误,但不是同一个,它在该块第一行的冒号之后给了我一个,并用红色突出显示整个空白区域......我不知道为什么。我把它放在 shell 中,这样它就可以突出自我并帮助我,而是向我展示完全不同的东西。

任何帮助将不胜感激!谢谢!

【问题讨论】:

  • 应该是def __init__,带双下划线,而不是_init_
  • 你肯定少了一个圆括号,"dy=" 行的结尾

标签: python


【解决方案1】:

您忘记关闭括号了。

通常,当您忘记关闭某些括号时,解释器会将错误指向以下行:

def _init_(self, x, y, size):
    """ Initialize asteroid sprite. """
    super(Asteroid, self)._init_(    <-- here you have a parentheses opening
        image = Asteroid.images[size],
        x = x, y = y,
        dx = random.choice([1, -1]) * Asteroid.SPEED * random.random()/size,
        dy = random.choice([1, -1]) * Asteroid.SPEED * random.random()/size  <-- no more commas here

    self.size = size  <-- first line without a trailing comma OR parentheses: SYNTAX ERROR HERE! (even though the assignment itself is ok)

也许这本书的实际意思是这样的——正如 Martijn Pieters 指出的那样,一些self.__init__ 参数(xy)被传递给父级的__init__ 方法,其他参数是正在其他地方阅读 (image) 或即时创建 (dxdy)。最后,其中一个参数(size)仅传递给实例,在self.__init__ 的主体中,分配给self.size

def __init__(self, x, y, size):
    """ Initialize asteroid sprite. """
    super(Asteroid, self)._init_(
        image = Asteroid.images[size],
        x = x,
        y = y,
        dx = (random.choice([1, -1]) * Asteroid.SPEED * random.random()/size),
        dy = (random.choice([1, -1]) * Asteroid.SPEED * random.random()/size))

    self.size = size

了解 Python 中的任何方法(在类中定义的例程)都会自动接收第一个参数,即对象实例本身,这一点很重要。尽管您可以随意称呼它,self 是通用的 Python 约定。因此,当您定义__init__ 并将self 作为第一个参数传递时,您可以在整个函数中使用它来引用您正在创建的对象。因此,说self.x = x 意味着您希望对象具有x 属性,其值是您在创建对象时传递的x 参数。

【讨论】:

  • 另外,我强烈建议你阅读 O'Reilly 的“Learning Python”,它的语言很轻松(有很多愚蠢的笑话和参考资料),让你真正理解“发生了什么”使用 Python 的工作方式。它对我帮助很大,是迄今为止我有机会阅读的最容易获得且最完整的 Python 学习资源。
  • 感谢你们到目前为止的帮助。我想有了你们提供给我的信息,我现在可以解决它!令人讨厌的是如何在编程中总是错过你错过的小东西:P.
猜你喜欢
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 2016-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多