我是对象的新手,想知道是否可以通过传递给函数的变量名来调用类。
def check_bonus(self, class_name="game"):
self.cls = class_name
if len(game.played_rounds_list) == 10:
if game.played_rounds_list[9].type == "Strike":
print("Last round strike - 2 more balls")
self.cls()
if game.played_rounds_list[10].type == "Strike":
print("1 ball remaining")
self.cls("Bonus")
if game.played_rounds_list[9].type == "Spare":
print("Last round spare - 1 more ball")
self.cls("Bonus")
我尝试了这种方法,但是遇到了错误: TypeError:“ str”对象不可调用
我该怎么做才能调用变量函数
答案 0 :(得分:1)
类是python中的对象。因此,例如,如果您的类在同一个文件中声明,则它是一个变量,您可以通过以下方式访问它:
game_cls = globals()['game']
game_object = game_cls(args)
但是,由于类是对象,所以最好不传递类名,而是传递类本身。因此,将您的功能更改为
def check_bonus(self, cls):
self.cls = cls
并通过
调用my_object.check_bonus(Game)