root
root

Reputation: 80346

Subclassing in python and __init__ : practical example

In python I can do this:

import mechanize
class MC (object):
      def __init__(self):
          self.Browser = mechanize.Browser()          
          self.Browser.set_handle_equiv(True)
      def open (self,url):
          self.url = url
          self.Browser.open(self.url)

My question is: how can I __init__ a parent class method in a subclass (that is something like this):

class MC (mechanize.Browser):
      def __init__(self):
          self.Browser.set_handle_equiv(True)

Help much appriciated!

Upvotes: 0

Views: 564

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121494

Just call the method directly, methods on base classes are available on your instance during initialisation:

class MC(mechanize.Browser):
    def __init__(self):
        self.set_handle_equiv(True)

You probably want to call the base-class __init__ method as well though:

class MC(mechanize.Browser):
    def __init__(self):
        mechanize.Browser.__init__(self)
        self.set_handle_equiv(True)

We need to call the __init__ directly because Browser is an old-style python class; in a new-style python class we'd use super(MC, self).__init__() instead, where the super() function provides a proxy object that searches the base class hierarchy to find the next matching method you want to call.

Upvotes: 2

Related Questions