python - 在 python 中使用 OOP 定义属性
问题描述
我目前在 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
代码按预期工作
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()
推荐阅读
- firebase-realtime-database - 如果用户关闭窗口或选项卡,如何保存对 firebase 文档的更改
- java - 我想根据从微调器中选择的值从特定的数组列表中获取元素
- react-native - undefined 不是对象(评估 '_expo.Permission.askAsync')
- python - 用一行在python中获取数组的元素
- php - 如何访问另一个数组中的数组
- git - 当工作分支不使用子模块时,如何合并来自包含子模块的 git 分支的更改
- javascript - 如何使用 JavaScript+React 处理条件运算符?
- javascript - 如何将两个 JavaScript 文件链接在一起?没有 HTML
- numpy - Miniconda 是否也受益于 numpy 的 MKL 优化?
- r - 如何在使用 rvest 和 stringr 从 R 中的网站抓取数据时遍历大量 ID?