简体   繁体   中英

How to change a class attribute into an instance attribute Python Programming

I need some help changing the class atribute size to a instance attribute. This is the current code(which works):

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")

When I try changing the class into an instance attribute like this:

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")

So from now on, instead of calling onto size with BoardHandler.size I call on self.size. But the error I get is:

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

What happens is the following. With

    self.size = self.ask_size()

the method ask_size takes the user input, converts it to an int , and stores it in self.size . The method then returns None , and that value is subsequently stored in self.size , as per the line quoted above. Net result: self.size contains None . Solution: either just call self.ask_size() , or modify self.ask_size() to return the size instead of setting it.

Your code is just fine, the problem is that you are using self.size when it is still to None ,return the value from the asking function instead of setting the self.size :

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM