如何从静态 属性 引用静态方法
How do I reference static methods from a static property
我正在尝试从字典中调用函数 - operation_functions
- key 是数学运算的名称
- 值是计算器 class 中执行数学运算的静态方法
当我尝试引用 operation_functions 中的函数时,它告诉我“未定义计算器”
我只想知道在同一个 class
中引用静态方法和静态 属性 的 pythonic 方式是什么
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()
在创建 class 后分配 operation_functions
以便您可以引用 class 名称。
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,
}
我正在尝试从字典中调用函数 - operation_functions
- key 是数学运算的名称
- 值是计算器 class 中执行数学运算的静态方法
当我尝试引用 operation_functions 中的函数时,它告诉我“未定义计算器”
我只想知道在同一个 class
中引用静态方法和静态 属性 的 pythonic 方式是什么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()
在创建 class 后分配 operation_functions
以便您可以引用 class 名称。
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,
}