Cross class 变量只初始化一次

Cross class variable only initialized once

我在 Python 中遇到一些问题。 我在 class (STATIC) 中初始化一个变量 (basePrice)。该值是静态的,初始化需要一些工作,所以我只想做一次。另一个classItem,是一个被大量创建的class。 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,如下所示。

basePrice = difficultCalculation()

def difficultCalculation():
    # details of implementation

# you can add other methods and classes and variables

然后,在包含 Item 的文件中,您可以:

from STATIC import basePrice

这将允许从该文件中的任何位置访问 basePrice