3

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'>
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Periodic Maintenance
  • 1,698
  • 4
  • 20
  • 32
  • Related: http://stackoverflow.com/questions/961048/get-class-that-defined-method. – alecxe Jan 17 '16 at 13:59
  • @alecxe I saw that link, it's not relevant to my question since 1) both Base and Derived have __init__ method so relaying on the name is not helpful. 2) I would like to know the defining class from within the __init__ method, and for any level of inheritance. – Periodic Maintenance Jan 17 '16 at 14:10

1 Answers1

2

Solution 1

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'>

Solution 2

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'>
Mike Müller
  • 82,630
  • 20
  • 166
  • 161