Skip to content

__init__(self) in Python

The init method within a class is run each time a new instance of the class is created.  These are used to set initial values and attributes.

Lets say we have a script called anExample.py

class className(object):

  def __init__(self):

    print 'I run each time my class is executed'

  def customMethod(self):

    print "I won't run unless im called"

Then we call this class from the python command line:

import anExample as ex
ex.className()
Output: I run each time my class is executed

But you wont see the string output from the customMethod() method, as it would need to be called to execute.

Published inPyCharmPythonscripting