Home > Net >  How do I reference static methods from a static property
How do I reference static methods from a static property

Time:11-26

I am trying to call functions from a dictionary - operation_functions

  • key is the name of a math operation
  • value is the staticmethod within the Calculator class that performs the math operation

When I try and reference the functions in operation_functions it tells me "Calculator is not defined"

I just want to know what is the pythonic way of referencing a staticmethod and static property from within the same class

class Calculator:
    """ This is the Calculator class"""

    operation_functions = {
        "addition": Calculator.add_number,
        "subtraction": Calculator.subtract_number,
        "multiplication": Calculator.multiply_number,
        "division": Calculator.divide_number,
    }

    @staticmethod
    def calculate_numbers(operation, *vals):
        """ will call respective calculation functions based on operation """
        function = Calculator.operations[operation]
        return function(*vals)

    @staticmethod
    def add_number(*vals):
        """ performs addition and returns resulting value """
        History.add_addition_calculation(*vals)
        return Calculator.get_last_result()

CodePudding user response:

Assign operation_functions after the class is created so you can refer to the class name.

class Calculator:
    """ This is the Calculator class"""

    @staticmethod
    def calculate_numbers(operation, *vals):
        """ will call respective calculation functions based on operation """
        function = Calculator.operations[operation]
        return function(*vals)

    @staticmethod
    def add_number(*vals):
        """ performs addition and returns resulting value """
        History.add_addition_calculation(*vals)
        return Calculator.get_last_result()

Calculator.operation_functions = {
    "addition": Calculator.add_number,
    "subtraction": Calculator.subtract_number,
    "multiplication": Calculator.multiply_number,
    "division": Calculator.divide_number,
}
  • Related