我最近一直在重構我的一些代碼以使用 OOP,但我遇到了一個問題,即我無法讓全域變數exec(), 或兩者的組合作業。相關代碼如下:
# invObject class. Has all properties of an inventory object.
class invObject:
def __init__(self, name, info, output, effect):
self.name = name # Used in menus.
self.info = info # Describes effect.
self.output = output # Printed on use.
self.effect = effect # Executed on use.
def printInfo(self): # Function for name and description.
return "{} - {}".format(self.name, self.info)
def use(self): # Function to use items. It's that easy.
global dodgeChance
global maxHp
global hp
global atk
exec(self.effect)
print(self.output) # Prints output. Also very simple.
print("{} {} {} {}".format(dodgeChance, maxHp, hp, atk)) # debugging
...
inventory[slot].use() # does not update values
基本綱要:inventory[slot].use()應該呼叫use()物件的函式。use()應該執行存盤在inventory[slot].effect.
除錯行的輸出不會改變任何東西,即使在函式內部也是如此。我已經嘗試過,但return exec(self.effect)無濟于事。print(self.output)確實有效。
編輯:這是一個最小的可重現示例,其中包括運行所需的所有內容,而不僅僅是最重要的內容。
# Assign base stats
dodgeChance = 0
maxHp = int(input("Input maximum HP. > "))
hp = int(input("Input current HP. > "))
# invObject class. Has all properties of an inventory object.
class invObject:
def __init__(self, name, info, output, effect):
self.name = name # Used in menus.
self.info = info # Describes effect.
self.output = output # Printed on use.
self.effect = effect # Executed on use.
def printInfo(self): # Function for name and description.
return "{} - {}".format(self.name, self.info)
def use(self): # Function to use items. It's that easy.
global dodgeChance
global maxHp
global hp
global atk
exec(self.effect)
print(self.output) # Prints output. Also very simple.
print("{} {} {} {}".format(dodgeChance, maxHp, hp, atk)) # debugging
empty = invObject("None", "Vacant slot.", "There's nothing in that slot!", "")
apple = invObject("Apple", "Gives 20 health.", "Ate the apple. Gained 20 health.", "hp = hp 20\nif hp > maxHp: hp = maxHp")
drink = invObject("Drink", "Some kind of energy drink. Raises dodge chance to 75%.", "Drank the drink. Dodge chance is now 75%!", "dodgeChance = 75")
# Assign base inventory
inventory = [apple, drink, empty]
slot = int(input("Input slot number to use. ")) - 1
inventory[slot].use() # does not update values
# Show final stats
print("New HP value: " str(hp))
print("Dodge chance: " str(dodgeChance) "%")
print()
print("Inventory contents:")
print("Slot 1: " str(inventory[0].name))
print("Slot 2: " str(inventory[1].name))
print("Slot 3: " str(inventory[2].name))
編輯 2:另一件事:如果我不使用 exec(),代碼可以作業(例如,將其更改為 hp = 20)。
uj5u.com熱心網友回復:
exec()有可選引數供您提供全域和區域變數背景關系。
但是你沒有提供它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440083.html
