【问题标题】:Calling a class by a variable in python在python中通过变量调用类
【发布时间】:2018-08-13 17:55:51
【问题描述】:

我是对象新手,想知道是否可以通过函数传递的变量名来调用类。

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' 对象不可调用

我必须做什么才能调用变量函数

【问题讨论】:

  • 您是否尝试过传递类本身,而不是代表类名的字符串?查看您的代码,您可能实际上想要传入一个对象,而不是一个类。或者可能是一个函数。 “呼叫”是什么意思?你真的想通过一个类,你可以从中制作一个对象吗?还是一个对象,你可以使用属性和方法?
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。

标签: python class oop object variables


【解决方案1】:

类是python中的对象。因此,例如,如果您的类在同一个文件中声明,它就是一个变量,您可以通过

game_cls = globals()['game']
game_object = game_cls(args)

但是,由于类是对象,因此最好不要传递类名,而是传递类本身。因此,将您的功能更改为

def check_bonus(self, cls):
    self.cls = cls

并调用它

my_object.check_bonus(Game)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2021-07-08
    • 1970-01-01
    • 2016-12-03
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    相关资源
    最近更新 更多