通过python类外部的函数更改类中变量的值

问题描述 投票:0回答:2

我正在尝试使用该类外部的函数来修改位于类内部的变量(在这种情况下为整数)的值。但是,当我调用该函数时,变量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

关于如何解决此问题的任何想法?

python python-3.x class global-variables
2个回答
0
投票
这是一个适合您的示例。

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


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.