以下 Python 3.5 代码:
class Base(object):
def __init__(self):
print("My type is", type(self))
class Derived(Base):
def __init__(self):
super().__init__()
print("My type is", type(self))
d = Derived()
打印:
My type is <class '__main__.Derived'>
My type is <class '__main__.Derived'>
我想知道,在每个 __init__() 中,定义方法的类,而不是派生类。所以我会得到以下打印:
My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>
请您参考如下方法:
方案一
使用super().__thisclass__:
class Base(object):
def __init__(self):
print("My type is", super().__thisclass__)
class Derived(Base):
def __init__(self):
super().__init__()
print("My type is", super().__thisclass__)
d = Derived()
My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>
解决方案2
类作品不那么优雅但硬连线:
class Base(object):
def __init__(self):
print("My type is", Base)
class Derived(Base):
def __init__(self):
super().__init__()
print("My type is", Derived)
d = Derived()
输出:
My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>
