【问题标题】:Python appending class with constructor带有构造函数的 Python 附加类
【发布时间】:2013-10-22 11:22:53
【问题描述】:

我正在使用 python 定义一个类,然后将它的一个实例附加到一个列表中。

class town:
    def __init__(name_, x_, y_, mayor_):
        name = name_
        main_x = x_
        main_y = y_
        mayor = mayor_
        desc = desc_

def add_town(name_, x_, y_, mayor_):
    towns.append(town(name_, x_, y_, mayor_))
    town_number += 1

def onCommand():
    add_town(args[1], loc_x, loc_y, sender.getName())

onCommand()

很遗憾,执行 add_town 时出现此错误:

原因:Traceback(最近一次调用最后一次):文件“”, 第 95 行,在 onCommandTown 文件“”中,第 74 行,在 add_town TypeError: init() 正好接受 4 个参数(给定 5 个)

注意:这是我用来简化代码的简化版本。请放心,所有变量都已正确定义。

编辑:此外,城镇是一个列表。

有人知道为什么会出现这个错误吗?我已经困惑了半个小时了,什么也没发生……

【问题讨论】:

标签: python list class constructor append


【解决方案1】:

将您的 __init__ 更改为

def __init__(name_, x_, y_, mayor_):

def __init__(self, name_, x_, y_, mayor_):

此外,您可能必须将初始化参数设为类变量。

def __init__(self, name_, x_, y_, mayor_):

    self.name = name_
    self.main_x = x_
    self.main_y = y_
    self.mayor = mayor_
    self.desc = desc_

并在类方法中以self.name 等形式访问它。

阅读更多this here

【讨论】:

  • 非常感谢,一切都很好。有什么方法可以定义一个“self”命名空间,这样我就不必不断输入 self.x 了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 2021-07-05
  • 2015-04-22
  • 1970-01-01
相关资源
最近更新 更多