有没有一种简单的方法可以在 class 中全球化变量
Is there an easy way to globalize a variable in a class
我想知道是否有一种简单的方法可以将 python class 中的变量全球化。我正在尝试下面的示例,但收到以下错误消息:
UnboundLocalError: 局部变量 'gold' 在赋值前被引用
我不想在每个函数中都键入 'global gold'。
gold = 10
class economy:
global gold
def income(self):
gold+=5
def expense(self):
gold-=5
class 中最容易访问的变量是一个属性,要在 class 之外使用它,您可以像这样创建一个 getVariable 函数:
gold = 10
class economy:
gold = None
def __init__(self,gold) :
self.gold = gold
def income(self):
self.gold+=5
def expense(self):
self.gold-=5
def getGold(self) :
return self.gold
# to get the gold value from the object :
gold = economy(gold).getGold()
最好把金币放在class,并从实例中引用
class economy:
def __init__(self, gold):
self.gold = gold
def income(self):
self.gold+=5
def expense(self):
self.gold-=5
a = economy(90)
a.income()
a.gold # 95
a.expense()
a.gold # 90
我想知道是否有一种简单的方法可以将 python class 中的变量全球化。我正在尝试下面的示例,但收到以下错误消息:
UnboundLocalError: 局部变量 'gold' 在赋值前被引用
我不想在每个函数中都键入 'global gold'。
gold = 10
class economy:
global gold
def income(self):
gold+=5
def expense(self):
gold-=5
class 中最容易访问的变量是一个属性,要在 class 之外使用它,您可以像这样创建一个 getVariable 函数:
gold = 10
class economy:
gold = None
def __init__(self,gold) :
self.gold = gold
def income(self):
self.gold+=5
def expense(self):
self.gold-=5
def getGold(self) :
return self.gold
# to get the gold value from the object :
gold = economy(gold).getGold()
最好把金币放在class,并从实例中引用
class economy:
def __init__(self, gold):
self.gold = gold
def income(self):
self.gold+=5
def expense(self):
self.gold-=5
a = economy(90)
a.income()
a.gold # 95
a.expense()
a.gold # 90