我对Python中的作用域有一些问题。
我初始化一个类(STATIC
)中的变量(basePrice
)。这个值是静态的,初始化需要一些工作,所以我只想做一次。另一个类Item
,是一个创建了很多的类。一个Item
对象需要使用basePrice
计算其变量price
。如何只初始化一次basePrice
并在Item
对象中使用它?在
class STATIC:
basePrice = 0
def __init__(self):
self.basePrice = self.difficultCalculation()
def getBasePrice()
return self.basePrice
import STATIC
class Item:
price = 0
def __init__(self,price_):
self.price = price_ - STATIC.getBasePrice()
最好写一个模块。例如,创建文件
STATIC.py
,如下所示。在然后,在包含
^{pr2}$Item
的文件中,可以执行以下操作:这将允许从该文件中的任何位置访问
basePrice
。在相关问题 更多 >
编程相关推荐