What is an object in Python

In Python, an object is an instance of a class that contains data (attributes) and methods (functions) that operate on that data.

An object is created when a class is instantiated, which means that memory is allocated to store the object’s data and methods. Once an object is created, it can be used to perform operations by calling its methods or accessing its attributes.

For example, consider a class called “Person” that has attributes such as “name” and “age”, and methods such as “say_hello”. When an instance of the Person class is created, it becomes an object that contains its own values for the “name” and “age” attributes. The “say_hello” method can be called on this object to perform some action, such as printing a greeting message.

In Python, everything is an object, including built-in data types such as integers, strings, and lists. This means that they also have attributes and methods that can be accessed and used.

Creating an Object of class:

To create an object of a class in Python, you need to follow these steps:

  1. Define the class: First, you need to define the class and its attributes and methods using the class keyword.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def say_hello(self):
        print("Hello, my name is", self.name)
  1. Instantiate the object: Once you have defined the class, you can create an object of that class by calling the class name followed by parentheses. This is called “instantiating” the object.
person1 = Person("Alice", 25)

In the above example, we create an object person1 of the Person class and pass the arguments “Alice” and 25 to the __init__ method, which initializes the object with the given values for the name and age attributes.

  1. Accessing attributes and methods: Once you have created an object of the class, you can access its attributes and methods using the dot notation.
print(person1.name)    # Output: Alice
person1.say_hello()    # Output: Hello, my name is Alice

In the above example, we access the name attribute of person1 using the dot notation (person1.name) and call the say_hello method using the dot notation (person1.say_hello()).