如何将类属性更改为实例属性Python编程

时间:2017-08-01 08:30:19

标签: python python-3.x

我需要一些帮助将类属性size更改为实例属性。 这是当前的代码(有效):

class BoardHandler:
    size=None
    def __init__ (self):
        self.board = None

        if BoardHandler.size is None:
            self.ask_size()
        self.getNewBoard()

    def ask_size(self):  
        while True:
            try:
                BoardHandler.size = int(input("Which size would you want? "))
                break
            except ValueError:
                print("Wrong! try again")

当我尝试将类更改为如下的实例属性时:

class BoardHandler:
    def __init__ (self):
        self.board = None
        self.size = self.ask_size()
        self.getNewBoard()

    def ask_size(self):  
        while True:
            try:
                self.size = int(input("Which size would you want? "))
                break
            except ValueError:
                print("Wrong! try again")

从现在开始,我没有使用BoardHandler.size调用size,而是调用self.size。但我得到的错误是:

Traceback (most recent call last):

  File "/Users//Desktop/REVERSI/.py", line 281, in <module>
    menu()
  File "/Users//Desktop/REVERSI/.py", line 213, in meny
    main1v1() 
  File "/Users//Desktop/REVERSI/.py", line 236, in main1v1
    handler = BoardHandler()
  File "/Users//Desktop/REVERSI/.py", line 35, in __init__
    self.newBoard()
  File "/Users//Desktop/REVERSI/.py", line 50, in newBoard
    for i in range(self.size):
TypeError: 'NoneType' object cannot be interpreted as an integer

2 个答案:

答案 0 :(得分:2)

以下是发生的事情。与

    self.size = self.ask_size()

方法ask_size接受用户输入,将其转换为int,并将其存储在self.size中。然后,该方法返回None,该值随后将根据上面引用的行存储在self.size中。最终结果:self.size包含None。解决方案:要么只是致电self.ask_size(),要么修改self.ask_size()以返回尺寸而不是设置它。

答案 1 :(得分:0)

您的代码很好,问题是当self.size仍在使用时None,请求函数返回值而不是设置self.size:< / p>

class BoardHandler:
    def __init__ (self):
        self.board = None
        self.size = self.ask_size()
        self.getNewBoard()

    def ask_size(self):  
        while True:
            try:
                size = int(input("Which size would you want? "))
                return size
            except ValueError:
                print("Wrong! try again")