从方法中确定定义 class
Determine the defining class from within a method
以下Python3.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__()
中,定义方法的 class,而不是派生 class。所以我会得到以下打印:
My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>
解决方案 1
使用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
不那么优雅,但 hard-wiring class 有效:
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'>
以下Python3.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__()
中,定义方法的 class,而不是派生 class。所以我会得到以下打印:
My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>
解决方案 1
使用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
不那么优雅,但 hard-wiring class 有效:
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'>