Google News
logo
Python Program to Create object methods
In the following example of Python program that demonstrates creating an object with methods :
Program :
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

    def celebrate_birthday(self):
        self.age += 1
        print(f"It's my birthday! I am now {self.age} years old.")

# Create a Person object
person = Person("Alice", 25)

# Call the greet() method
person.greet()

# Call the celebrate_birthday() method
person.celebrate_birthday()

# Call the greet() method again to see the updated age
person.greet()
Output :
Hello, my name is Alice and I am 25 years old.
It's my birthday! I am now 26 years old.
Hello, my name is Alice and I am 26 years old.
In this example, we created a `Person` class with an `__init__()` method that initializes the `name` and `age` attributes. We also created two additional methods: `greet()` and `celebrate_birthday()`.

We then created a `Person` object named `person` with the name "Alice" and the age 25. We called the `greet()` method on `person`, which prints a greeting with the person's name and age. We then called the `celebrate_birthday()` method on `person`, which increments the person's age by 1 and prints a message announcing the birthday.

Finally, we called the `greet()` method again to see the updated age.