Tuesday 7 June 2011

Python Class - Am I a subclass?

Problem...
in #python on freenode, a question was asked about identifying a subclass during the __init__ method.
I came up with this example. 
class Example(object):
    def __init__(self):
        if self.__class__ != Example.mro()[0]:
            print "I am an instance of a subclass of Example"
        else:
            print "I am an instance of Example"

class ExampleDeritive(Example):
    ''' the most basic of subclasses! '''
    pass


>>> Example()
I am an instance of Example

>>> ExampleDeritive()
I am an instance of a subclass of Example

No comments: