我正在尝试根据传入的字符串调用类中的函数。
我尝试按照此链接中的步骤操作: Calling a function of a module from a string with the function's name in Python
这是我的代码:
methodNameString = "add" + typeOfShip
methodToCall = getattr(listOfPlayerFleets[currentPlayer], methodNameString)
listOfPlayerFleets[currentPlayer].methodToCall(num)
我得到错误:
AttributeError:fleet instance has no attribute 'methodToCall'
关于为什么没有为 methodToCall 分配我正确的方法名称的任何想法?
我也试过
methodToCall = getattr(fleet, methodToCall)
然后我收到消息:
AttributeError: 'module' object has no attribute 'addCruiser'
好像 getattr 在我的课堂上找不到我的方法。
listOfPlayerFleets 是舰队对象的列表
这是舰队对象的样子,您可以看到这些方法确实存在。
class fleet:
""" Stores Fleet Numbers, Represents a fleet """
ships = {'fighters':0, 'cruisers':0, 'capitols':0}
attacking = False
defending = False
def __init__(self):
self.ships = {'fighters':0, 'cruisers':0, 'capitols':0}
self.attacking = False
self.defending = False
#add a Fighter
def addFighter(self, numOfFighters):
self.ships['fighters'] = numOfFighters
#add a Cruiser
def addCruiser(self, numOfCruisers):
self.ships['cruisers'] = numOfCruisers
#add a Capitol Ship
def addCapitol(self, numOfCapitols):
self.ships['capitols'] = numOfCapitols