【发布时间】:2023-03-05 20:56:01
【问题描述】:
尝试将 转换为简单的 super(B, self).method()bubble() 调用。
做到了,see below!
在这个例子中是否可以引用 B 类?
class A(object): pass
class B(A):
def test(self):
test2()
class C(B): pass
import inspect
def test2():
frame = inspect.currentframe().f_back
cls = frame.[?something here?]
# cls here should == B (class)
c = C()
c.test()
基本上,C 是 B 的孩子,B 是 A 的孩子。然后我们创建C 类型的c。然后对c.test() 的调用实际上调用了B.test()(通过继承),它调用了test2()。
test2()可以得到父框架frame;通过frame.f_code 对方法的代码引用;
self 通过frame.f_locals['self'];但type(frame.f_locals['self']) 是C(当然),但不是B,其中定义了方法。
有什么方法可以得到B?
【问题讨论】:
-
如果我可以问...你需要这个做什么?因为我几乎不认为这样的事情可能是任何事情的最佳方法。
-
我实际上是在尝试通过某种简单的
bubble()调用来简化用户的super(B, self).test()操作。其实我已经找到办法了。 -
你不能
super(self.__class__, self).test()吗? -
@WoLpH:不,因为第一个参数可能是“这个类”而不是
self.__class__,它可能是“这个类”的子类。如果这样可行,为什么 Python 不自己这样做并消除第一个参数是多余的? -
@Slava:Python 3 中的 AFAIK
super可以不带参数调用。虽然我猜你想要 Python 2.x。
标签: python