在类中使用字符串调用函数



我有一个字符串,我想用它来调用一个类中的函数。

class TimeValue:
def __init__(self, *args):
self.args = args
def PV(self):
FV,r,n  = self.args
return f"$ {FV/(1+(r/100))**(n):.3f}"

def FV(self):
PV,r,n  = self.args
return f"$ {PV*(1+(r/100))**(n):.3f}"
def Annuity(self):
C,r,n  = self.args
return f"$ {(C/(r/100)) * (1-(1/(1+(r/100)) ** (n-1))):.3f}"
def Perpetuity():
pass
inv_comp = input("Enter a desired investment computation (PV, FV, Annuity, Perpetuity) ")
obj = TimeValue(*req_values)
###------------###
print(obj.locals()["inv_comp"]())
###------------###

这里的问题是python想要调用locals(),它不是类中的函数。我如何使用inv_comp直接调用类中的函数?

使用getattr:

getattr(obj, inv_comp)()
注意,您希望使用变量inv_comp,而不是字符串字面值"inv_comp"

getattr函数接受一个字符串(类似于"PV"或用户输入的任何东西),并返回obj中与该名称匹配的属性,因此:

getattr(obj, "PV")

等价于:

obj.PV

如果inv_comp不是现有属性的名称,则会引发AttributeError,就像您在代码中键入属性名称一样。