为什么我的对象没有属性?

why is it that my object has no attribute?

我是 Python 的新手(几天前开始),我一直在尝试编写大富翁代码(参考不同用户的代码),但我似乎无法通过具体错误指出我的 'Game' 对象没有属性 'square_number'

import random

class rolling(object):

    def roll(self):
        return random.randint(1, 6)


class Player(object):
    PlayerList = []
    SquareNum = []
    other = []

    def __init__(self, name):
        self.name = name
        self.balance = 1500
        self.square_number = 0
        self.square_name = None
        Player.other.append(self)
        Player.PlayerList.append(self.name)
        Player.SquareNum.append(self.square_number)
        print(self.name, "successfully added \n")
    #    print(self.square_number, "assigned")
    #    print(Player.SquareNum)

    def roll_and_move(self):
        dice1 = rolling.roll(self)
        dice2 = rolling.roll(self)
        totaldice = dice1 + dice2
        if dice1 == dice2:
            print("YOU LANDED A DOUBLE!")

        if totaldice + self.square_number >= len(Game.Board_Squares):
            pass
        else:
            self.square_number = self.square_number + totaldice
            self.square_name = Game.Board_Squares[self.square_number - 1]

        print(Game.current_player, "rolled", dice1, "and", dice2, "moving " + str(totaldice) + " spaces")
        print(Game.current_player, "is on", self.square_name, "\n")
        Player.PlayerList.sort(key=Player.PlayerList[0].__eq__) # first player in the list moves to last player in the list
        Game.running_game(self)


class Game(object):
    def __init__(self):
        Game.Board_Squares = ['Mediterranean Avenue', 'Community Chest 1', 'Baltic Avenue', 'Income Tax', 'Reading Railroad',
                         'Oriental Avenue', 'Chance 1', 'Vermont Avenue', 'Connecticut Avenue', 'Just Visiting Jail',
                         'St. Charles Place', 'Electric Company', 'States Avenue', 'Virginia Avenue', 'Pennsylvania Railroad',
                         'St. James Place', 'Community Chest 2', 'Tennessee Avenue', 'New York Avenue', 'Free Parking',
                         'Kentucky Avenue', 'Chance 2', ' Indiana Avenue', 'Illinois Avenue', 'B. & O. Railroad',
                         'Atlantic Avenue', 'Ventnor Avenue', 'Water Works', 'Marvin Gardens', 'Go To Jail', 'Pacific Avenue',
                         'North Carolina Avenue', 'Community Chest 3', ' Pennsylvania Avenue', 'Short Line', 'Chance 3',
                         'Park Place', 'Luxury Tax', 'Boardwalk', 'Go']

        print("Welcome to Monopoly!")
        n = int(input("Enter the number of players: "))
        if n > 8:
            print("You may only have 8 players!")
        elif n == 0:
            print("You may not have 0 players!")
        else:
            for i in range(0, n):
                i += 1
                names = input("Player" + str(i) + ": ")
                Player(names)
               # Player.PlayerList.append(names)
            self.running_game()

    def running_game(self):
        Game.current_player = Player.PlayerList[0] # current player is first in the list
        input("\x1B[3mPress ENTER to continue\x1B[0m\n")
        Player.roll_and_move(self)


Game()

老实说,我不知道我一直在努力做什么。我似乎无法完全查明问题,这使得找到解决方案变得更加困难。我注意到,当我的 'roll_and_move' 被调用时,带有 'self.' 的任何东西似乎都不起作用,并且似乎想转到我的 'Game' class.

您的“游戏”class只有构造方法和running_game方法。 “square_number”在播放器class中,初始化时可用。

在上面的代码中,我注意到您试图在不初始化对象的情况下调用 class 方法。例如,

dice1 = rolling.roll(self)
dice2 = rolling.roll(self)
# should be
# dice1 = rolling().roll()
# dice2 = rolling().roll()
# notice the parenthesis () after rolling which indicates that rolling class is initialized and method roll can then be called.

Player.roll_and_move(self) 
# this should be Player(name="test").roll_and_move()

我建议您阅读更多关于 class、对象初始化、方法的内容。

此答案从 classes、对象和实例的概念开始。 由于代码中的几个问题,它没有回答原始问题。

A class 是对象的模板。对象是 class 的实例。 因此,所需的初始代码更改是创建 Game() class.

的实例

已在以下代码的最后一行完成。

已添加其他注释和注释代码以供参考。

import random


class rolling(object):

    def roll(self):
        return random.randint(1, 6)


class Player(object):
    PlayerList = []
    SquareNum = []
    other = []

    def __init__(self, name):
        self.name = name
        self.balance = 1500
        self.square_number = 0
        self.square_name = None
        Player.other.append(self)
        Player.PlayerList.append(self.name)
        Player.SquareNum.append(self.square_number)
        print(self.name, "successfully added \n")

    #    print(self.square_number, "assigned")
    #    print(Player.SquareNum)

    def roll_and_move(self):
        dice1 = rolling.roll(self)
        dice2 = rolling.roll(self)
        totaldice = dice1 + dice2
        if dice1 == dice2:
            print("YOU LANDED A DOUBLE!")
        # To help understand issues break the code down into smaller pieces
        # Get the number of board squared from the Game class.
        number_of_board_squares = len(Game.Board_Squares)
        # Get the square number from the curren tplayer instance
        player_current_square_number = self.square_number  # error because
        # there is no instance of Player for self to refer to.
        if totaldice \
                + self.player_current_square_number \
                >= number_of_board_squares:
            pass
        else:
            self.square_number = self.square_number + totaldice
            self.square_name = Game.Board_Squares[self.square_number - 1]

        print(Game.current_player, "rolled", dice1, "and", dice2,
              "moving " + str(totaldice) + " spaces")
        print(Game.current_player, "is on", self.square_name, "\n")
        Player.PlayerList.sort(key=Player.PlayerList[
            0].__eq__)  # first player in the list moves to last player in the list
        Game.running_game(self)


class Game(object):
    def __init__(self):
        Game.Board_Squares = ['Mediterranean Avenue', 'Community Chest 1',
                              'Baltic Avenue', 'Income Tax',
                              'Reading Railroad',
                              'Oriental Avenue', 'Chance 1', 'Vermont Avenue',
                              'Connecticut Avenue', 'Just Visiting Jail',
                              'St. Charles Place', 'Electric Company',
                              'States Avenue', 'Virginia Avenue',
                              'Pennsylvania Railroad',
                              'St. James Place', 'Community Chest 2',
                              'Tennessee Avenue', 'New York Avenue',
                              'Free Parking',
                              'Kentucky Avenue', 'Chance 2', ' Indiana Avenue',
                              'Illinois Avenue', 'B. & O. Railroad',
                              'Atlantic Avenue', 'Ventnor Avenue',
                              'Water Works', 'Marvin Gardens', 'Go To Jail',
                              'Pacific Avenue',
                              'North Carolina Avenue', 'Community Chest 3',
                              ' Pennsylvania Avenue', 'Short Line', 'Chance 3',
                              'Park Place', 'Luxury Tax', 'Boardwalk', 'Go']

        print("Welcome to Monopoly!")
        n = int(input("Enter the number of players: "))
        if n > 8:
            print("You may only have 8 players!")
        elif n == 0:
            print("You may not have 0 players!")
        else:
            for i in range(0, n):
                i += 1
                names = input("Player" + str(i) + ": ")
                Player(names)
            # Player.PlayerList.append(names)
            self.running_game()  # start the current game instance.

    def running_game(self):
        # Game.current_player = Player.PlayerList[0] # current player is first in the list
        input("\x1B[3mPress ENTER to continue\x1B[0m\n")
        Player.roll_and_move(self)


new_game = Game()  # Create an instance of a game