How to define constructor for a class

What is a constructor

The constructor is a method which is called automatically right after an object has been created.

In Python we use __init__ as the constructor name.


class FooBar:#   w w w  .j  a va 2  s  .  c  o  m
    def __init__(self):
        self.somevar = 42

f = FooBar()
print f.somevar

The code above generates the following result.

The following code has a constructor with named parameter.


# from  w w w .  jav a  2 s.com
class FooBar:
    def __init__(self, value=42):
        self.somevar = value

f = FooBar('This is a constructor argument')
print f.somevar

The code above generates the following result.

Modifying Class Attributes


class counter:# from   w w w .jav  a  2 s  . c  om
    count = 0
    def __init__(self):
        self.__class__.count += 1

counter
print counter.count
c = counter()
print c.count
print counter.count
d = counter()
print d.count
print c.count
print counter.count

Constructor with default parameter


class grocery:# ww w. ja va  2s  .  c om
    def __init__(self, name, quantity=1):
        self.name = name
        self.quantity = quantity

items = {}
items['A'] = grocery('A')
items['B'] = grocery('B',2)

for item in items.keys():
  print "Grocery : ", items[item].name,
  print "\tQuantity: ", items[item].quantity

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules