Periodic Maintenance
Periodic Maintenance

Reputation: 1777

Determine the defining class from within a method

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

Answers (1)

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85442

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

Upvotes: 2

Related Questions