liv2hak
liv2hak

Reputation: 15010

def __init__(self, *args, **kwargs) initialization of class in python

I am new to Python. I came across Python code in an OpenFlow controller that I am working on.

class SimpleSwitch(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(SimpleSwitch, self).__init__(*args, **kwargs)
        self.mac_to_port = {}

My questions are as follows.

  1. Is __init__ the constructor for a class?

  2. Is self the same as C++'s this pointer?

  3. Does super(SimpleSwitch, self).__init__(*args, **kwargs) mean calling constructor for parent/super class?

  4. Can you add a new member to self as mac_to_port? Or has that been already added and just being initialized here?

Upvotes: 6

Views: 20513

Answers (2)

nameisnotphil
nameisnotphil

Reputation: 1

  1. Super in Python is not like C++'s super. I have not used C++, but I can tell you that super in python does not act the same. Instead of calling the parent, python super calls the children of the class in which super is called, then moves in an interesting chain. Think of three tiered class system where there is a single base class, two subclasses to that base class, and two subclasses to those subclasses. Calling super on the bottom tier would call the parent immediately above it, but calling super in one of the second-tier classes would call their children first, then it looks to the side and calls the other classes on it's own tier, then the children of that same-tier class are called. Once all of the same-tier classes and all of their children re called, then super calls the parent of the middle-tier classes.

It's hard to explain in words. Watch Raymond Hettinger's "super considered super" talk from PyCon. He gives a very good explanation of how it works, and why python's super should not be called 'super'.

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122091

  1. __init__ is the initialiser; __new__ is the constructor. See e.g. this question.
  2. Effectively yes: the first argument to instance methods in Python, called self by convention, is the instance itself.
  3. Calling the parent class's initialiser, yes.
  4. It's adding a new attribute to SimpleSwitch in addition to what the parent class already has, an empty dictionary.

Upvotes: 8

Related Questions