[英]Defining attributes using OOP in python
I am currently using OOP in python to program a game.我目前在 python 中使用 OOP 来编写游戏。 I have created a class with attributes and methods.
我创建了一个带有属性和方法的 class。 I wanted to do basic movement where if the user types "go north" it will move to the north square.
我想做基本的移动,如果用户输入“向北”,它将移动到北广场。 However it is saying i have an error and that north isn't defined.
然而,它说我有一个错误,北方没有定义。 Here is my code:
这是我的代码:
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()
Thanks谢谢
You are missing self
in various places for the code to work as intended您在各个地方都缺少
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()
Try using self.north.尝试使用 self.north。
square.movement(action, self.north)
You are trying to use a variable called north which isn't set.您正在尝试使用未设置的名为 north 的变量。 But you do have the variable north in your class which you have to acces via self.<variable_name>.
但是您的 class 中确实有变量 north,您必须通过 self.<variable_name> 访问它。
I hope it solves your problem我希望它能解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.