📘

Python Class Constructors

Jul 18, 2024

Python Class Constructors

Overview

  • Fundamental part of object-oriented programming
  • Create and initialize objects, making them ready for use
  • Triggers Python's instantiation process: Instance creation and initialization

Objective of the Course

  • Understand Python's internal instantiation process
  • Customize object initialization using __init__
  • Fine-tune object creation by overriding __new__
  • Requires knowledge of OOP and special methods in Python

The Instantiation Process

  • Class Keyword:
    • Define custom classes with attributes (data) and methods (behavior)
  • Object Construction/Instantiation:
    • Creating new instances of the class

Class Constructor

  • Call the class with arguments
  • Creates, initializes, and returns a new object
  • Calling a class ≠ calling an instance of a class
    • __call__ special method makes an instance callable

Steps of Instantiation

  1. Creating the Instance: __new__ method
  • Responsible for creating and returning a new empty object
  1. Initializing the Instance: __init__ method
  • Takes the new object and initializes with attributes

Example

  • Empty Class: class SomeClass: pass instance = SomeClass()
  • Custom Initialization: class Point: def __new__(cls, *args, **kwargs): instance = super().__new__(cls) return instance def __init__(self, x, y): self.x = x self.y = y
    • __new__ creates object, __init__ initializes x and y

Deep Dive: Object Initialization with __init__

Basics of __init__

  • Most common special method to override
  • Assigns input arguments to instance attributes

Example

  • Rectangle Class: class Rectangle: def __init__(self, width, height): self.width = width self.height = height
  • Ensures width and height are initialized

Argument Validation

  • Validate arguments in __init__ class Rectangle: def __init__(self, width, height): if width <= 0 or height <= 0: raise ValueError("Width and height must be positive") self.width = width self.height = height
  • Enhance validation with properties

Using super() in Subclasses

  • Extend functionality in subclass while calling base class __init__ class Person: def __init__(self, name, birthdate): self.name = name self.birthdate = birthdate class Employee(Person): def __init__(self, name, birthdate, position): super().__init__(name, birthdate) self.position = position

Flexibility in __init__

Optional Arguments

  • Use default argument values for flexible initializers class Greeter: def __init__(self, name, formal=False): self.name = name self.formal = formal def greet(self): greeting = "Hello, " if self.formal else "Hi, " return f"{greeting}{self.name}"
    • Allows instantiation with different sets of arguments

Upcoming: Deep Dive into __new__

  • Understanding and customizing the object creation step