【问题标题】:Cross class variable only initialized once跨类变量只初始化一次
【发布时间】:2016-04-29 11:51:15
【问题描述】:

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

【问题讨论】:

  • 你为什么要为此使用一个类?只需进行一次计算并将其存储在全局变量中,例如base_price.
  • 或者,如果 STATIC 类有其他行为,也许可以考虑创建一个单例类。
  • 关于单例类,您可以将base_price 转储为模块中的全局变量,而不是类,该模块在程序的生命周期内仅加载一次。这里也建议:stackoverflow.com/questions/31875/…
  • 这确实更有意义。如果您在名为STATIC.py 的文件中将basePrice 声明为全局变量,则只需执行from STATIC import basePrice
  • 我认为 global 关键字仅表示该变量在该类或模块中是全局的?

标签: python variables scope global


【解决方案1】:

编写一个模块可能会更好。例如,创建文件STATIC.py,如下所示。

basePrice = difficultCalculation()

def difficultCalculation():
    # details of implementation

# you can add other methods and classes and variables

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

from STATIC import basePrice

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

【讨论】:

  • 哦,我明白了。我没想过导入变量。谢谢!
猜你喜欢
  • 2015-08-23
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2013-06-04
相关资源
最近更新 更多