我正在尝试使用该类外部的函数来修改位于类内部的变量(在这种情况下为整数)的值。但是,当我调用该函数时,变量us_balance
的值保持不变:42
。
class Country:
us_balance = 42
def buy(country, amount):
if country.lower == "us":
Country.us_balance = Country.us_balance - amount
def stats():
print(Country.us_balance)
while True:
user_input = input("> ").lower()
if user_input == "buy":
amount = input("$ ").lower()
balance_to_set = amount.split()
buy(balance_to_set[0], int(balance_to_set[1]))
if user_input == "stats":
stats()
break
关于如何解决此问题的任何想法?
class Country:
us_balance = 42
def buy(ci, country, amount):
if country.lower() == "us":
new = ci.us_balance = ci.us_balance - amount
ci.us_balance = new
def stats(ci):
print(ci.us_balance)
# Create an instance of the class
ci = Country()
while True:
user_input = input("> ").lower()
if user_input == "buy":
amount = input("$ ").lower()
balance_to_set = amount.split()
buy(ci, balance_to_set[0], int(balance_to_set[1]))
if user_input == "stats":
stats(ci)
break