0% found this document useful (0 votes)
23 views4 pages

Python Class Methods

The document explains various Python class methods including __init__, __str__, __repr__, __len__, and __getitem__. Each method is illustrated with examples demonstrating its purpose, such as object creation, string representation, debugging, length retrieval, and item access. These methods enhance the functionality and usability of Python classes.

Uploaded by

yoeurthsaiyann20
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)
23 views4 pages

Python Class Methods

The document explains various Python class methods including __init__, __str__, __repr__, __len__, and __getitem__. Each method is illustrated with examples demonstrating its purpose, such as object creation, string representation, debugging, length retrieval, and item access. These methods enhance the functionality and usability of Python classes.

Uploaded by

yoeurthsaiyann20
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/ 4

Python Class Methods

1.
__init__(self)
The
__init__
method is the constructor in Python. It's automatically called when a new object is created.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p = Person("John", 30)
print(p.name) # John

2.
__str__(self)
The
__str__
method returns a string representation of the object that is readable and user-friendly.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name}, {self.age} years old"

p = Person("Alice", 25)
print(p) # Alice, 25 years old

3.
__repr__(self)
The
__repr__
method provides a formal string representation of the object, mainly used for debugging.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"

p = Person("Bob", 40)
print(repr(p)) # Person('Bob', 40)

4.
__len__(self)
The
__len__
method is used to return the length of the object, similar to how
len()
works.

class MyList:
def __init__(self, items):
self.items = items

def __len__(self):
return len(self.items)
lst = MyList([1, 2, 3])
print(len(lst)) # 3

5.
__getitem__(self, key)
The
__getitem__
method allows you to access items in an object, like dictionary or list indexing.

class MyDict:
def __init__(self):
self.data = {"a": 1, "b": 2}

def __getitem__(self, key):


return self.data[key]

d = MyDict()
print(d['a']) # 1

You might also like