猿问

Python TypeError:range()整数结尾参数预期错误

我有以下代码,并且在某些时候我想初始化


具有行和列范围的对象。


当我同时打印它们时,据我所知,每个数字都有一个数字


它应该适用于range方法。


这是代码:


class Board(object):

    def __init__(self, rows, columns):


        #small values

        if rows < 1 or columns < 2:

            SizeOutOfBoundException


        #large values

        if rows > 20 or columns > 50:

            SizeOutOfBoundException


        self.rows = rows;

        self.columns = columns; 

        self.arr = [[[0,'H'] for x in range(self.rows)] for y in range(self.columns)] # <- ERROR

但这是我不断得到的错误:


self.arr = [[[0,'H'] for x in range(self.rows)] for y in range(self.columns)] 

TypeError: range() integer end argument expected, got Board.

我如何操纵它才能工作?为什么这行不通?


手掌心
浏览 342回答 3
3回答

慕码人8056858

这对我有用。您确定问题不在于缩进吗?您的构造函数未正确缩进。class Board(object):&nbsp; &nbsp; def __init__(self, rows, columns):&nbsp; &nbsp; &nbsp; &nbsp; #small values&nbsp; &nbsp; &nbsp; &nbsp; if rows < 1 or columns < 2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise SizeOutOfBoundException&nbsp; &nbsp; &nbsp; &nbsp; #large values&nbsp; &nbsp; &nbsp; &nbsp; if rows > 20 or columns > 50:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise SizeOutOfBoundException&nbsp; &nbsp; &nbsp; &nbsp; self.rows = rows&nbsp; &nbsp; &nbsp; &nbsp; self.columns = columns&nbsp; &nbsp; &nbsp; &nbsp; self.arr = [[[0,'H'] for x in range(self.rows)] for y in range(self.columns)]myboard = Board(3,4)print myboard.arr输出为:[[[0,'H'],[0,'H'],[0,'H']],[[0,'H'],[0,'H'],[0,'H' ]],[[0,'H'],[0,'H'],[0,'H']],[[0,'H'],[0,'H'],[0,' H']]]

慕盖茨4494581

您很可能Board以行或列而不是整数的形式传递对象。印刷:self.rowsself.columnstype(self.rows)type(self.columns)就在导致错误的行之前可以帮助确认这一点,或者您可以张贴正在使用的调用Board(rows,columns)的代码吗?

侃侃尔雅

您要实例化课程吗?b = Board(10, 10)print b.arr
随时随地看视频慕课网APP

相关分类

Python
我要回答