0% found this document useful (0 votes)
3 views2 pages

Init_and_Str_Methods_Python

__init__ and __str__ are special dunder methods in Python that control object behavior. The __init__ method initializes an object's attributes upon creation, while __str__ provides a user-friendly string representation when the object is printed. Both methods enhance the usability and readability of objects in Python programming.

Uploaded by

Sumadhur
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)
3 views2 pages

Init_and_Str_Methods_Python

__init__ and __str__ are special dunder methods in Python that control object behavior. The __init__ method initializes an object's attributes upon creation, while __str__ provides a user-friendly string representation when the object is printed. Both methods enhance the usability and readability of objects in Python programming.

Uploaded by

Sumadhur
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
You are on page 1/ 2

Special Methods in Python: __init__ and __str__

Python has special methods called dunder methods (double underscore), like __init__ and __str__.

These methods control object behavior.

__init__ Method - The Constructor

- What it does: Initializes an object's attributes when it is created.

- When it runs: Automatically called when you create an object using the class.

Example:

class Student:

def __init__(self, name, age):

self.name = name

self.age = age

s1 = Student("Amit", 15)

print(s1.name) # Output: Amit

print(s1.age) # Output: 15

Notes:

- __init__ is optional but commonly used.

- The first parameter is always self (refers to the current object).

__str__ Method - String Representation

- What it does: Returns a readable string when you print an object.

- When it runs: Automatically called when using print() or str() on the object.
Example:

class Student:

def __init__(self, name, age):

self.name = name

self.age = age

def __str__(self):

return f"Student Name: {self.name}, Age: {self.age}"

s1 = Student("Amit", 15)

print(s1) # Output: Student Name: Amit, Age: 15

Notes:

- Without __str__, print shows a memory address.

- Helps make object output user-friendly.

Quick Comparison Table:

| Method | Purpose | When It's Called |

|------------|--------------------------------------|--------------------------------|

| __init__ | Initializes object attributes | When an object is created |

| __str__ | Returns readable string of object | When print() or str() is used |

You might also like