Skip to content

Python class constructors

A Python class constructor is a special method used to initialize instances of a class.^[400-devops-09-scripting-language-python-introduction-readme.md] In Python, this is defined using the __init__ method^[400-devops-09-scripting-language-python-introduction-readme.md], which allows objects to be created with specific initial values rather than setting attributes individually after creation^[400-devops-09-scripting-language-python-introduction-readme.md].

Definition

The constructor method is declared within a class body using the syntax def __init__(self, ...):.^[400-devops-09-scripting-language-python-introduction-readme.md] The __init__ method is automatically called when a new instance of the class is created^[400-devops-09-scripting-language-python-introduction-readme.md].

Initialization Logic

The primary purpose of the constructor is to assign initial values to the object's properties.^[400-devops-09-scripting-language-python-introduction-readme.md] It accepts arguments that are passed during the object's instantiation and assigns them to the instance's attributes using the self keyword^[400-devops-09-scripting-language-python-introduction-readme.md]. For example, a constructor for a Customer class might accept customerID, firstName, and lastName as parameters^[400-devops-09-scripting-language-python-introduction-readme.md].

Example

The following code demonstrates a class definition that includes a constructor to initialize a customer object with default values^[400-devops-09-scripting-language-python-introduction-readme.md]:

class Customer:
  def __init__(self, c="", f="", l=""):
    self.customerID = c
    self.firstName  = f
    self.lastName   = l
  def fullName(self):
    return self.firstName + " " + self.lastName

marcel = Customer("h", "Marcel", "Dempers")
print(marcel.fullName())
  • [[Classes and Objects]]
  • [[Object-oriented programming]]

Sources

  • 400-devops-09-scripting-language-python-introduction-readme.md