Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
实例化Python类时遇到问题_Python - Fatal编程技术网

实例化Python类时遇到问题

实例化Python类时遇到问题,python,Python,我很抱歉要问这个问题,因为已经有很多关于这个主题的文章,但是我在将它应用到一个具体的项目中时遇到了很多困难 我们的目标是创建一个MarblesBoard类,该类接受一组数字作为输入,然后玩一个游戏来排列这些数字 这是我的密码: class MarblesBoard: def _init_(self, numbers): self.board = [] for i in numbers: board[i] = numbers[i]

我很抱歉要问这个问题,因为已经有很多关于这个主题的文章,但是我在将它应用到一个具体的项目中时遇到了很多困难

我们的目标是创建一个MarblesBoard类,该类接受一组数字作为输入,然后玩一个游戏来排列这些数字

这是我的密码:

class MarblesBoard:

    def _init_(self, numbers):
        self.board = []
        for i in numbers:
            board[i] = numbers[i]

    def switch():
        temp = board[0]
        board[0] = board[1]
        board[1] = temp


def main():
    board = MarblesBoard((3,4,5))
    print("I'm here")
因此,将数字作为元组输入,将其放入数组中,然后像在switch方法中一样对其进行操作


但是当我使用main方法时,我无法打印任何内容。

您的代码有很多问题。我想这是你的第一堂python课

首先,主要应该是课外活动。init与两个ux一起使用。引用成员变量时,必须始终使用self。因为i在数字中是关于数字本身的循环,而不是它们的索引。当foo是一个空数组时,不能在python中只分配foo[i]=bar,我认为在其他语言中也可以。在类上创建成员方法时,它们必须始终将self作为第一个参数

class MarblesBoard:

    def __init__(self, numbers):
        self.board = []
        for i in numbers:
            self.board.append(i)


    def switch(self):
        # Fixing this left as an exercise for the OP


if __name__=="__main__":
        board = MarblesBoard((3,4,5))
        print("I'm here")
第一个修复是函数,它有两个前导下划线和尾随下划线

def __init__(self, numbers):
2您正在尝试将元组中的数字插入空列表,使用每个元素的元组作为索引位置,这将引发索引错误

例如:-

>>> board = []
>>> numbers = (3,4,5)
>>> for i in numbers:
...     board[i] = numbers[i]
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: tuple index out of range
3如果switch是您的实例方法,则必须将self作为第一个参数传递

def switch(self):
    temp = self.board[0]
    #Your logic
所以,毕竟这是它应该看起来的样子

class MarblesBoard:

    def __init__(self, numbers):
        self.board = numbers

    def switch(self):
        temp = self.board[0]
        # your logic

def main():
    board_obj = MarblesBoard((3,4,5))
    print("I'm here")
    print board_obj.board

main()
在主功能的位置使用

if __name__ == '__main__':
    board_obj = MarblesBoard((3,4,5))
    print("I'm here")
    print board_obj.board  

这是你的实际缩进吗?还有,还有更多的代码吗?也就是说,你真的打电话给梅因吗?Python与C/C++/Java不同,C/C++/Java以main作为神奇的入口点。我删除了我的答案,因为这段代码有太多错误。@Ted请查看答案,如果需要更改,请告诉我。如果您觉得答案是正确的或对您有帮助,请点击正确的符号提出并接受答案。
if __name__ == '__main__':
    board_obj = MarblesBoard((3,4,5))
    print("I'm here")
    print board_obj.board