general summary
In Python, classes provide a means to bundle data and methods, facilitating easy code organization. They serve as blueprints from which objects are created.
A Python class encompasses data and related operations, helping to represent real-world entities or more abstract concepts.
Key Features
Inheritance
New classes can be derived from existing ones to represent a more specialized relationship.
Encapsulation
Class internals are shielded from external access, influencing the data through methods.
Polymorphism
Objects of different classes can be treated uniformly in shared interfaces.
Reusability
Functions and methods created in one class can be reused across the entire class.
Example: Car Class
class Car:
# Class attribute
car_count = 0
# Constructor
def \_\_init\_\_(self, make, model, year, is_running=False):
# Instance attributes
self.make = make
self.model = model
self.year = year
self.is_running = is_running
Car.car_count += 1
# Instance method
def start(self):
self.is_running = True
print(f"{self.make} {self.model} started.")
# Instance method
def stop(self):
self.is_running = False
print(f"{self.make} {self.model} stopped.")
# Class method
@classmethod
def about(cls):
return f"This car class represents vehicles. Total cars: {cls.car_count}"Instantiating the Class
You can create unique instances of a class using a process called instantiation
# Create two car objects
car1 = Car("Toyota", "Corolla", 2015)
car2 = Car("Ford", "Fiesta", 2022)
Each object now has its own state
print(f"{car1.make} {car1.model} is running: {car1.is_running}") # Output: False
print(f"{car2.make} {car2.model} is running: {car2.is_running}") # Output: False
Start the cars
car1.start()
car2.start()
Check their state again
print(f"{car1.make} {car1.model} is running: {car1.is_running}") # Output: True
print(f"{car2.make} {car2.model} is running: {car2.is_running}") # Output: True
Access and modify class attribute
print(Car.car_count) # Output: 2Using Class Methods
It is possible to invoke methods that are directly associated with the class itself
Class methods often serve to manage class-level attributes or perform actions related to the class, rather than individual instances.
about = Car.about() print(about) # Output: This car class represents vehicles. Total cars: 2