【发布时间】: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