What is the difference between __init__ and __call__?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Difference Between __init__ and __call__ in Python

In Python, __init__ and __call__ are special methods, but they serve different purposes in the object lifecycle and behavior. Understanding their differences is key to using them effectively when designing classes.

__init__: The Constructor Method

  • Purpose: __init__ is the constructor method in Python, used to initialize a newly created object. It's called automatically when a new instance of a class is created.

  • When it is called: It is invoked when a new instance of the class is instantiated.

  • Role: It sets up the initial state of the object (i.e., initializes instance variables or performs setup tasks).

  • Return value: It doesn't return anything (i.e., implicitly returns None).

  • Syntax:

    class MyClass: def __init__(self, param): self.param = param

Example:

class Person: def __init__(self, name, age): self.name = name self.age = age # Creating an instance of Person person1 = Person("Alice", 30) print(person1.name) # Output: Alice print(person1.age) # Output: 30

Explanation:

  • The __init__ method is called when person1 is created. It initializes the name and age attributes.

__call__: The Callable Object Method

  • Purpose: __call__ allows an instance of a class to be called like a function. When you use parentheses () with an object, Python checks for the __call__ method.

  • When it is called: It is invoked when an instance is called directly (e.g., object()).

  • Role: It makes the object behave like a function, which is useful when you want the object to perform specific actions or computations when "called".

  • Return value: __call__ can return any value, just like a normal function.

  • Syntax:

    class MyClass: def __call__(self, *args, **kwargs): # Perform some action print("Object is called with arguments:", args)

Example:

class Adder: def __init__(self, start_value): self.start_value = start_value def __call__(self, number): return self.start_value + number # Creating an instance of Adder add_five = Adder(5) # Calling the object like a function result = add_five(10) # Output: 15 print(result) # Output: 15

Explanation:

  • The __call__ method allows the add_five object to be used like a function, adding the argument to its start_value.

Key Differences

Feature__init____call__
PurposeInitializes an object's attributes when it is created.Makes an object callable like a function.
When CalledAutomatically when a new object is instantiated.When an instance is called using parentheses.
Primary UseObject construction (initialization of state).Defining behavior when the object is called.
Return ValueNo return value (implicitly returns None).Can return a value (similar to a function).
Example Use CaseSetting up an object's state upon creation.Using an object as a function (e.g., for callbacks or computation).

Practical Comparison

__init__ Example:

class Counter: def __init__(self, start): self.count = start def increment(self): self.count += 1 counter = Counter(0) counter.increment() print(counter.count) # Output: 1

Here, __init__ is used to initialize the count attribute when the object is created.

__call__ Example:

class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, number): return number * self.factor multiply_by_two = Multiplier(2) result = multiply_by_two(5) # Output: 10 print(result) # Output: 10

Here, __call__ makes the multiply_by_two object callable, just like a function, multiplying its argument by the factor attribute.

Conclusion

  • __init__ is the initializer (constructor) that sets up the object when it is created, setting the initial state.
  • __call__ makes the object callable, turning it into a function-like object that performs actions when used with parentheses.

Understanding both methods allows you to design flexible and powerful Python classes that can behave in ways beyond traditional object modeling.

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How can I improve my behavioral interview?
Does Microsoft benefit from OpenAI?
Which skill is required of a data engineer?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.