Classes and objects are the foundation of Object-Oriented Programming (OOP). A class is a blueprint for creating objects, and an object is an instance of a class.
To create a class, you use the class
keyword:
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 an object of the class
person1 = Person("Alice", 25)
person1.greet()
The __init__
method is the constructor that initializes an object, and the greet
method is a function that belongs to the class.
Create a Car
class with attributes make
and model
, and a method that prints the car's information.
__init__
method in Python classes?Answers: A class is a blueprint for creating objects, while an object is an instance of the class. The __init__
method initializes the attributes of the object when it is created.