Python - OOP - Object Oriented Programming - Part 3
Object methods are functions defined inside a class and are used to manipulate the object's state. They operate on an object's data attributes and can be used to modify, retrieve or update the object's attributes. Some commonly used object methods in Python include __init__, __str__, __repr__, __del__, and many others.
Here is a basic example of defining and using object methods in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
def set_age(self, new_age):
self.age = new_age
def __str__(self):
return f"{self.name} is {self.age} years old."
person1 = Person("John", 30)
print(person1.get_name()) # Output: John
print(person1.get_age()) # Output: 30
person1.set_age(40)
print(person1.get_age()) # Output: 40
print(person1) # Output: John is 40 years old.
In this example, we defined a Person class with four object methods: __init__, get_name, get_age, and set_age. The __init__ method is a special method that gets called when an object is created and is used to initialize the object's attributes. The get_name and get_age methods are used to retrieve the object's name and age attributes, respectively. The set_age method is used to update the object's age attribute. Finally, the __str__ method is used to represent the object as a string.
We created an instance of the Person class called person1 with the name "John" and age 30. We then used the get_name and get_age methods to retrieve the person's name and age, respectively. We also used the set_age method to update the person's age to 40. Finally, we printed the person object using the __str__ method, which returns the person's name and age as a string.