2016-01-22 30 views
0

我在Python中遇到了一些麻煩。 我在一個類(STATIC)初始化變量(basePrice)。該值是靜態的,初始化需要一些工作,所以我只想做一次。另一個類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() 
+2

你爲什麼要用這個類?只需進行一次計算並將其存儲在全局變量中,例如'base_price'。 – kindall

+0

或者,如果類「STATIC」有其他行爲,可以考慮創建一個單例類。 –

+0

關於單例類,您可以將'base_price'作爲全局變量轉儲到模塊中,而不是在類中,該模塊在程序生命週期中只加載一次。這裏也建議:http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python –

回答

0

寫一個模塊可能會更好。例如,如下所示創建文件STATIC.py

basePrice = difficultCalculation() 

def difficultCalculation(): 
    # details of implementation 

# you can add other methods and classes and variables 

然後,在包含Item你的文件,你可以這樣做:

from STATIC import basePrice 

這將允許從該文件中的任何地方都訪問basePrice

+0

哦,我明白了。我沒有想過導入一個變量。謝謝! – Matthias