在python中使用OOP定义属性

在python中使用OOP定义属性,python,object,oop,Python,Object,Oop,我目前正在使用python中的OOP编程一个游戏。我创建了一个具有属性和方法的类。我想做一个基本的移动,如果用户类型向北移动,它将移动到北方广场。然而,它说我有一个错误,北方没有定义。这是我的密码: class square(): def __init__(self, action, square_no, north, east, south, west): self.action = action self.square_no = sq

我目前正在使用python中的OOP编程一个游戏。我创建了一个具有属性和方法的类。我想做一个基本的移动,如果用户类型向北移动,它将移动到北方广场。然而,它说我有一个错误,北方没有定义。这是我的密码:

class square():
    def __init__(self, action, square_no, north, east, south, west):
        
        self.action = action
        self.square_no = square_no
        self.north = north
        self.east = east
        self.south = south
        self.west = west

    def user_action(action):
        action = input("---").lower()

        square.movement(action, north)

    def Help():
        print("Commands are: \n Go(north/ east /south /west) \n Mine \n Craft (object) \n Look around \n Collect (blueprint)\n Fix (wing/ thruster/ engine/ battery/ fuel tank) \n Save \n Info \n You will see this symbol when you are expected to type something ---")
        square.user_action(action)

    def movement(action, north):
             
        if action == "go north":
            print(north)

        elif action == "info":
            square.Help()   
            
        else:
            print("You can't do that here.")
            square.user_action(action)


action = ""

square1 = square(action, 1, 0, 2, 4, 0)
print(square1)

square1.user_action()
谢谢

尝试使用self.north

square.movement(action, self.north)
您正在尝试使用一个名为north的变量,该变量未设置。但是你的类中确实有变量north,你必须通过self访问它

我希望它能解决您的问题

您在不同的地方缺少了自我,代码无法正常工作

class square():
    def __init__(self, action, square_no, north, east, south, west):
        
        self.action = action
        self.square_no = square_no
        self.north = north
        self.east = east
        self.south = south
        self.west = west

    def user_action(self):
        action = input("---").lower()

        self.movement(action)

    def Help(self):
        print("Commands are: \n Go(north/ east /south /west) \n Mine \n Craft (object) \n Look around \n Collect (blueprint)\n Fix (wing/ thruster/ engine/ battery/ fuel tank) \n Save \n Info \n You will see this symbol when you are expected to type something ---")
        self.user_action(action)

    def movement(self,action):
             
        if action == "go north":
            print(self.north)

        elif action == "info":
            square.Help()   
            
        else:
            print("You can't do that here.")
            square.user_action(action)


action = ""

square1 = square(action, 1, 0, 2, 4, 0)
print(square1)
square1.user_action()

您的实例方法需要实例本身的self参数,然后您可以访问self.north。这将修复它,谢谢!这有帮助,谢谢