Search code examples
pythonpython-2.6

Python how to get the base instance of an instance?


In C# I would go:

myObj.base

I have a Date class which inherits from date.datetime. The Date class overrides __gt__() and __lt__() so when using the < and > operators they are called. I do not want to use these overrides - I want to use the date.datetime methods on an instance of Date.


Solution

  • Use super() to get the superclass object. Type help(super) in the Python command prompt.

    From the manual:

    class super(object)
     |  super(type) -> unbound super object
     |  super(type, obj) -> bound super object; requires isinstance(obj, type)
     |  super(type, type2) -> bound super object; requires issubclass(type2, type)
     |  Typical use to call a cooperative superclass method:
     |  class C(B):
     |      def meth(self, arg):
     |          super(C, self).meth(arg)
    

    Let class B be a subclass of class A and class A have a method def f(self)::

    • In Python 2, you can call a superclass method in class A from derived class B by using super(B, self).f().
    • In Python 3, you can use super().f() without the B, self arguments.