[Python] Efficient use of constants in multiple class instances

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    Class A has some methods where constant values are needed. Assuming multiple instances of class A need to be created, which option would be more efficient/cleaner?

    Option 1 (constants outside of class):

    CT_A = 1.0
    CT_B = 2.0
    ...

    class A:

    def __init__(self):
    ...

    def method_class(self):
    return CT_A * (CT_B + 10.0) # Simple example of constant use


    Option 2 (constants inside of class):

    class A:

    CT_A = 1.0
    CT_B = 2.0

    def __init__(self):
    ...

    def method_class(self):
    return self.CT_A * (self.CT_B + 10.0) # Simple example of constant use


    Option 3 (Class inheritance):

    class Constants:
    CT_A = 1.0
    CT_B = 2.0

    class A(Constants):

    def __init__(self):
    ...

    def method_class(self):
    return Constants.CT_A * (Constants.CT_B + 10.0) # Simple example of constant use


    Code optimization is an issue in the project I need to implement this on as class A is a class to be used for several unit tests, hence the need to reduce computational cost.

    In reality there are 5 or 6 constants, not just one or two as in this example.

    Continue reading...

Compartilhe esta Página