Google News
logo
Python Program to Create an object
To create an object in Python, first, we need to define a class. Then, we can create an instance of the class using the class name followed by parentheses. Here's an example :
Program :
# Define a class named Person
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

# Create an object of Person class
person1 = Person("John", 28)

# Access the attributes of person1 object
print("Name:", person1.name)
print("Age:", person1.age)
Output :
Name: John
Age: 28
In the above example, we have defined a class named "Person" with two attributes: "name" and "age". We have also defined a constructor (`__init__` method) which initializes these attributes.

Then, we have created an object of the "Person" class by calling the class name followed by parentheses. We have passed two arguments to the constructor of the class which are used to initialize the "name" and "age" attributes of the object.

Finally, we have accessed the attributes of the object using the dot notation.