Python Class Methods
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}
d = MyDict()
print(d['a']) # 1