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!

Answers


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.


Need Your Help

How to make UIAlertView call `alertViewShouldEnableFirstOtherButton:` after making changes?

ios cocoa-touch uialertview

I have a UIAlertView with a UITextField. I have connected the UIAlertView delegate and I return YES or NO in alertViewShouldEnableFirstOtherButton: depending on the text in the UITextField.

AngularJS testing with Jasmine unable to call “angular.mock.module” while using angular-mocks.js

javascript unit-testing angularjs jasmine

I'm trying to get a basic unit test working and am running into an issue using angular-mocks.js. Hopefully this code will explain my situation.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.