Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 540
liv2hak Avatar asked Apr 12 '14 08:04

liv2hak


1 Answers

  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.
like image 191
jonrsharpe Avatar answered Sep 30 '22 19:09

jonrsharpe