In Python, a class is a blueprint for creating objects (instances). It defines a set of attributes (variables) and methods (functions) that characterize any object created from that class. An object, also known as an instance, is a specific realization of a class. Here’s an example to illustrate the concept of a class and object:
# Define a class named Person
class Person:
# Constructor method to initialize the object
def __init__(self, name, age):
self.name = name # Attribute: name
self.age = age # Attribute: age
# Method to greet the person
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create an object (instance) of the Person class
person1 = Person("Alice", 30)
# Access attributes and call methods of the object
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
person1.greet() # Output: Hello, my name is Alice and I am 30 years old.