Here’s an example of an object-oriented class in Python that represents a generic vehicle. This class will include a class attribute, local variables in methods, and will demonstrate the use of both local and global variables.
1. Class Definition
class Vehicle:
# Class attribute
total_vehicles = 0 # Keeps track of the number of Vehicle instances
def __init__(self, make, model, year):
# Instance attributes
self.make = make
self.model = model
self.year = year
Vehicle.total_vehicles += 1 # Increment class attribute whenever a new vehicle is created
def display_info(self):
# Local variables
info = f"{self.year} {self.make} {self.model}"
print(info)
return info
@classmethod
def vehicle_count(cls):
# Using class attribute to return the total number of vehicles created
return cls.total_vehicles
# Global variable
total_vehicle_instances = 0
# Function to create and manage vehicles
def create_vehicles():
global total_vehicle_instances # Use the global variable
vehicles = []
# Create vehicle instances
vehicle1 = Vehicle("Toyota", "Corolla", 2020)
vehicle2 = Vehicle("Honda", "Civic", 2021)
vehicle3 = Vehicle("Ford", "Mustang", 2022)
vehicles.append(vehicle1)
vehicles.append(vehicle2)
vehicles.append(vehicle3)
# Update global variable
total_vehicle_instances += len(vehicles)
# Display vehicle information
for vehicle in vehicles:
vehicle.display_info()
print(f"Total vehicles created: {Vehicle.vehicle_count()}")
print(f"Total vehicle instances (global): {total_vehicle_instances}")
# Run the vehicle creation function
create_vehicles()
Explanation:
-
Class Attribute: The
total_vehicles
class attribute is used to keep track of the number of instances (vehicles) created from theVehicle
class. -
Instance Attributes: The
__init__
method initializes a vehicle'smake
,model
, andyear
. -
Local Variables: In the
display_info
method, the local variableinfo
holds the formatted string representation of the vehicle information. -
Global Variables: The function
create_vehicles
utilizes a global variabletotal_vehicle_instances
to keep a count of all vehicle instances created during the execution of the function. -
Method Calls: The
create_vehicles
function creates several instances of theVehicle
class, displays their information, and also displays the total count of vehicle instances.
Usage
Copy the code into your Python environment (like PythonAnywhere) and run it. You will see the output of the vehicle information along with the count of total vehicles created both via the class method and the global variable.