Definition: A class is a blueprint or template for creating objects. It defines a set of attributes (variables) and methods (functions) that the objects created from the class will have.
Car class, attributes might include make, model, year, and color.Car class, methods might include start(), drive(), brake(), and honk().class Car:
def __init__(self, make, model, year, color):
self.make = make
self.model = model
self.year = year
self.color = color
def start(self):
print(f"The {self.color} {self.make} {self.model} is starting.")
def drive(self):
print(f"The {self.color} {self.make} {self.model} is driving.")
Definition: An object is an instance of a class. It is a specific realization of the class blueprint, containing actual data and capable of using the methods defined by the class.
Characteristics:
Car object, the state includes the values of make, model, year, and color.start() and drive() methods of a Car object.Creating and Using Objects: To create an object, you call the class as if it were a function, passing any necessary arguments to the __init__ method.
Example:
# Creating an object of the Car class
my_car = Car("Toyota", "Corolla", 2020, "blue")
# Accessing attributes
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
# Calling methods
my_car.start() # Output: The blue Toyota Corolla is starting.
my_car.drive() # Output: The blue Toyota Corolla is driving.
class Car:
# Constructor to initialize the attributes
def __init__(self, make, model, year):
self.make = make # Car make (e.g., Toyota)
self.model = model # Car model (e.g., Corolla)
self.year = year # Car manufacturing year
# Method to get the car description
def get_description(self):
return f"{self.year} {self.make} {self.model}"
# Method to simulate starting the car
def start(self):
return f"{self.get_description()} is starting."
# Method to simulate stopping the car
def stop(self):
return f"{self.get_description()} is stopping."
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla", 2021)
# Accessing attributes
print(f"Make: {my_car.make}")
print(f"Model: {my_car.model}")
print(f"Year: {my_car.year}")
# Calling methods
print(my_car.get_description())
print(my_car.start())
print(my_car.stop())
Make: Toyota
Model: Corolla
Year: 2021
2021 Toyota Corolla
2021 Toyota Corolla is starting.
2021 Toyota Corolla is stopping.
Car class is defined with an __init__ method, which is the constructor used to initialize the object’s attributes: make, model, and year.get_description method returns a formatted string describing the car.start method returns a string indicating that the car is starting.stop method returns a string indicating that the car is stopping.Car class is created with the name my_car and initialized with the make “Toyota”, model “Corolla”, and year 2021.make, model, and year of the my_car object are accessed directly and printed.get_description, start, and stop methods are called on the my_car object, and their results are printed.