Reputation: 1777
The following Python 3.5 code:
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()
prints:
My type is <class '__main__.Derived'>
My type is <class '__main__.Derived'>
I would like to know, inside each __init__()
, the class where the method was defined, not the deriving class. So I would get the following print:
My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>
Upvotes: 3
Views: 54
Reputation: 85442
Use 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'>
Not as elegant but hard-wiring the class works:
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()
Output:
My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>
Upvotes: 2