[英]Defining attributes using OOP in python
我目前在 python 中使用 OOP 來編寫游戲。 我創建了一個帶有屬性和方法的 class。 我想做基本的移動,如果用戶輸入“向北”,它將移動到北廣場。 然而,它說我有一個錯誤,北方沒有定義。 這是我的代碼:
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()
嘗試使用 self.north。
square.movement(action, self.north)
您正在嘗試使用未設置的名為 north 的變量。 但是您的 class 中確實有變量 north,您必須通過 self.<variable_name> 訪問它。
我希望它能解決你的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.