跨类变量仅在上初始化

2024-10-04 05:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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()

Tags: 对象importselfreturninitdef静态static
1条回答
网友
1楼 · 发布于 2024-10-04 05:28:53

最好写一个模块。例如,创建文件STATIC.py,如下所示。在

basePrice = difficultCalculation()

def difficultCalculation():
    # details of implementation

# you can add other methods and classes and variables

然后,在包含Item的文件中,可以执行以下操作:

^{pr2}$

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

相关问题 更多 >