0

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!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
root
  • 76,608
  • 25
  • 108
  • 120
  • One of the key concepts of object inheritance is that the child inherits all of the properties (attributes, methods) of the parent. Maybe you should look into an introduction to OOP, again :-) – Dr. Jan-Philip Gehrcke Sep 10 '12 at 14:09

1 Answers1

2

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.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    I don't know mechanize, but it seems likely that you might need to call `mechanize.Browser.__init__(self)` first to make sure the Browser is initialized properly. – mgilson Sep 10 '12 at 14:09
  • @Pieters: I actually tried this. What mgilson is suggesting solves the problem :) – root Sep 10 '12 at 14:11