0

I'm having some troubles with the scope in Python. I initialize a variable (basePrice) in a class (STATIC). The value is static and the initialization takes some work, so I only want to do it once. Another class Item, is a class that is created a lot. An Item object needs to calculate its variable price by using basePrice. How can I initialize basePrice only once and use it in an Item object?

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()
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Matthias
  • 5
  • 7
  • 2
    Why are you using a class for this? Just do the calculation once and store it in a global variable, e.g. `base_price`. – kindall Jan 22 '16 at 19:20
  • Or, if the class `STATIC` has other behavior, maybe think about creating a singleton class. – Jared Goguen Jan 22 '16 at 19:21
  • About the singleton class, instead of a class you can dump `base_price` as a global variable in a module, which is loaded only once during the lifetime of the program. It is also suggested here: http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python – Lauro Moura Jan 22 '16 at 19:23
  • That does make more sense. If you declare `basePrice` as a global variable in file named `STATIC.py`, you can just do `from STATIC import basePrice`. – Jared Goguen Jan 22 '16 at 19:27
  • I thought the global keyword only means the variable is global in that class or module? – Matthias Jan 22 '16 at 19:32

1 Answers1

0

It might be better to write a module. For example, create the file STATIC.py as shown below.

basePrice = difficultCalculation()

def difficultCalculation():
    # details of implementation

# you can add other methods and classes and variables

Then, in your file containing Item, you can do:

from STATIC import basePrice

This will allow all access to basePrice from anywhere within that file.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36