0

I want to calculate a value in the class that stays the same for all instances of that class and is calculated only once

class A:
    a = calculate_a()
    def calculate_a():
        return 5

first, What should I set as reference for calculate_a() in a = calculate_a() ? self.calculate_a() and A.calculate_a() both are not correct (unresolved reference) what I need is, when the second instance is created, the calculate_a() is not called again.

instance1 = A()  -> calls calculate_a() to set value for a;
instance2 = A()  -> uses the value of a calculated above without calling calculate_a
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

1 Answers1

0

Class members are only initialized once - they are initialized before (and without) instances being created.


You can test this yourself:

def calculate_a():
    print("Calculated")
    return 5

class A:   
    a = calculate_a()

Executing this prints 'Calculated' once, even without any creation of instances.

def calculate_a():
    print("Calculated")
    return 5

class A:   
    a = calculate_a()

input("Order?")
k = A()
i = A()
c = A()

Executing this print's 'Calculated' only once - and it does so right before asking for 'Order?' - after inputting the program ends wihtout any more outputs.


More infos:

You can put your "init"-method into a holder-class to avoid polluting global():

class A_base:
    @staticmethod
    def calculate_a():
        print("Calculated")
        return 5

class A:   
    a = A_base.calculate_a()
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69