【问题标题】:Using getattr to call a function in a separate class使用 getattr 调用单独类中的函数
【发布时间】:2018-03-21 06:51:19
【问题描述】:

我可能在这里尝试做一些超出可能性范围的事情,但我想在放弃希望之前我会先问清楚。就这样吧……

我有 2 个类,A 和 B。每个类都有任意数量的函数。 B 类将在 A 类的某处实例化,A 类将通过该实例利用 B 类函数之一。 B 类中的函数需要使用 A 类的当前实例化数据来引用 A 类的一个或多个函数。

A 类

#!/usr/bin/python
from classB import classB


class classA(object):
    def Apple(self):
        print("Inside Apple")
        b = classB()
        b.Banana()
        b.bar()

    def foo(self): 
        print("foo inside apple")


a = classA()
a.Apple()

B 类:

#!/usr/bin/python
import inspect


class classB(object):
    def Banana(self):
        print("Inside banana")

    def bar(self):
        print("bar inside banana")

        ''' 
        The following lines just show I can get the names of the
        calling class and methods.
        '''
        stack = inspect.stack()
        the_class = stack[1][0].f_locals["self"].__class__
        the_method = stack[1][0].f_code.co_name
        print("Caller Class: {}".format(the_class))
        print("Caller Method: {}".format(the_method))

        function_name = 'foo'
        if hasattr(the_class, function_name):
            print("Class {} has method {}".format(the_class, 
            function_name))
            getattr(the_class, function_name)()

我收到以下错误:

getattr(the_class, function_name)()

TypeError: unbound method foo() must be called with classA instance 作为第一个参数(什么都没有)

谢谢!

【问题讨论】:

  • 你的缩进被破坏了,请修复。
  • @StephenRauch 固定缩进。谢谢。显然不是我的来源的问题……只是在 SO 帖子中。
  • 是的,但是缩进让你很难理解你在做什么......
  • 你试过getattr(the_class, function_name)(the_class)吗?
  • @NilsWerner,是的,我收到以下错误:“TypeError: unbound method foo() must be called with classA instance as first argument (got type instance)”这让我觉得我可以得到实例不知何故......只是不确定在哪里。

标签: python python-2.7 class getattr hasattr


【解决方案1】:

正如错误提示的那样,在调用 getattr 之前,您必须构建一个 classA 对象(即 the_class)。

objA = the_class()

但是退后一步,为什么不在初始化时将 A 类传递给 B 类呢?

b = classB(self)

这将允许您访问所需的 A 类的确切方法。

否则,如果类 A 中的方法 'foo' 应该是静态方法,请使用 @staticmethod 装饰器使其成为静态方法。

【讨论】:

  • 完美!我什至不知道你能做到这一点,但这更有意义(指将 classA self 传递给 classB)。谢谢。
  • 第二段是这里重要的一段:你应该明确地将你需要的一切传递给一个类或方法
猜你喜欢
  • 2016-03-26
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多