0% found this document useful (0 votes)
4 views3 pages

Notes25 2

__init__() is a constructor method in Python that is automatically called upon object creation to initialize object attributes. It does not create the object itself, which is done by __new__(), and must not return anything other than None. The document provides examples of using __init__() with single and multiple attributes, as well as default values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Notes25 2

__init__() is a constructor method in Python that is automatically called upon object creation to initialize object attributes. It does not create the object itself, which is done by __new__(), and must not return anything other than None. The document provides examples of using __init__() with single and multiple attributes, as well as default values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

__init__()

What is __init__() ?

__init__() is a constructor method in Python.

It is automatically called when you create an object of a class.

Its main job is:

Initialize (set up) object data (attributes)

Basic Syntax
class ClassName:
def __init__(self, parameters):
# initialization code

• self → refers to the current object


• Runs immediately after object creation

Example 1: Simple Initialization


class Student:
def __init__(self, name):
[Link] = name

s1 = Student("Vijay")
print([Link])

Output:
Vijay

Explanation:

• Student("Vijay") → creates object


• __init__() is called automatically
• [Link] = name → stores "Vijay" inside object
Example 2: Multiple Attributes
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age

s1 = Student("Vijay", 22)

print([Link])
print([Link])

Output:
Vijay
22

Think of it like:

__init__() = filling a form when object is created

Example 3: Default Values


class Car:
def __init__(self, brand="Unknown"):
[Link] = brand

c1 = Car()
c2 = Car("Tesla")

print([Link])
print([Link])

Output:
Unknown
Tesla

Important Points

✔ __init__() is not responsible for creating object

• Object is created by __new__()

✔ It only initializes data

✔ It does not return anything


def __init__(self):
return None # implicit

Common Mistake
class Test:
def __init__(self):
return 10 # ERROR

__init__() must return None, otherwise error

Final Summary

__init__() is:

• Automatically called
• Used to initialize object data
• Runs after object creation
• Does not return anything

You might also like