Python Code Example: Introducing a Person

In this example, we define a class called Person that has a constructor method __init__ which takes two parameters: name and age. The constructor sets two instance variables name and age which are passed as arguments. We also define a method called introduce which prints out the name and age of the person.

We then create an object of the Person class called person1 by calling the class constructor with the arguments “Alice” and 25. Finally, we call the introduce method on the person1 object to print out its name and age.

This example demonstrates the basic concepts of classes and objects in Python. We create a blueprint for a Person object with the Person class, and then create an instance of that object with the person1 variable. We can then call methods on the person1 object to interact with it and access its data.

# Define a class called "Person"
class Person:
    
    # Define the class constructor method
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    # Define a method to introduce the person
    def introduce(self):
        print(f"Hi, my name is {self.name}, and I am {self.age} years old.")
        

# Create an object of the "Person" class
person1 = Person("David", 21)

# Call the "introduce" method on the object
person1.introduce() 
Output
Hi, my name is David, and I am 21 years old.