Python demonstrate working of classes and objects
Here you will get a python program to demonstrate working of classes and objects.
To demonstrate the working of classes and objects in Python, let’s create a simple example of class ‘Person’ and objects that represent different people.
Example of python program to demonstrate working of classes and objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name} and I am {self.age} years old.") # Create objects of the Person class person1 = Person("Ajay", 40) person2 = Person("Seema", 31) # Access object attributes and methods print(person1.name) # Output: Ajay print(person1.age) # Output: 40 person1.greet() # Output: Hello, my name is Ajay and I am 40 years old. print(person2.name) # Output: Seema print(person2.age) # Output: 31 person2.greet() # Output: Hello, my name is Seema and I am 31 years old. |
Explanation:
Class Definition:
>> The ‘Person’ class is defined using the ‘class’ keyword.
>> The __init__ method is a special method called a constructor. It initializes the object’s attributes (‘name’ and ‘age’) when a new object is created.
>> The ‘greet’ method is a regular method that prints a greeting message using the object’s attributes.
Creating Objects:
>> ‘person1’ and ‘person2’ are objects (or instances) of the ‘Person’ class.
>> They are created by calling the class as if it were a function, passing the required arguments for the ‘name’ and ‘age’ parameters.
Accessing Attributes and Methods:
>> The attributes of an object can be accessed using dot notation (e.g., person1.name).
>> Methods of an object can also be called using dot notation (e.g., person1.greet()).
Check out our other Python programming examples