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
- 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.
- The class also defines a method named print_details. This method simply prints the name and age of the person using the print function.
- An object of the Person class is created by calling the constructor with the arguments “John Snow” and 28.
- The person variable now refers to this object.
- 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 Student that inherits from the Person class.
Create a Python class called Cat that inherits from the Animal class.
Create a Python class called BankAccount with attributes account_number and balance.
Create a Python class called SavingsAccount that inherits from the BankAccount class.
Create a Python class called CheckingAccount that inherits from the BankAccount class.
Create a Python class called Car with attributes make, model, and year.