27. Problem to create a class with attributes in Python

In this Python oops program, we will create a class with attributes in Python. This code demonstrates the basic functionality of the Person class, allowing you to create person objects, store their name and age, and print their details.

Create a class with attributes 

Steps to solve the program
  1. The Person class is defined with a constructor method __init__. The constructor takes two parameters, name and age, which represent the name and age of the person, respectively. Inside the constructor, the values of name and age are assigned to the instance variables self.name and self.age, respectively.
  2. The class also defines a method named print_details. This method simply prints the name and age of the person using the print function.
  3. An object of the Person class is created by calling the constructor with the arguments “John Snow” and 28.
  4. The person variable now refers to this object.
  5. The print_details method is called on the person object, which prints the details of the person.
				
					class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)

# Create an object of the Person class
person = Person("John Snow", 28)
person.print_details()
				
			

Output:

				
					Name: John Snow
Age: 28
				
			

Related Articles

Create a Python class called Circle with attributes radius.

Create a Python class called Student that inherits from the Person class.

Leave a Comment