Welcome to the world of Object-Oriented Programming (OOP)! This topic is crucial for structuring complex applications and promoting reusability, readability, and maintainability in your code. Here's what you'll learn:
Object-Oriented Programming is a programming paradigm that revolves around objects, which can contain data and methods. An object is an instance of a class, a blueprint or template for creating such instances. Here are the key terms:
Let's create a simple class called Car
with attributes like brand
, model
, and year
. We will also include methods such as start_engine()
, accelerate()
, and brake()
.
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def start_engine(self):
print("Engine started.")
def accelerate(self):
print("Car is accelerating.")
def brake(self):
print("Car is braking.")
# Create an instance of the Car class
my_car = Car("Toyota", "Corolla", 2020)
my_car.start_engine() # Output: Engine started.
What causes it: Accessing an attribute that doesn't exist on the object.
my_car.non_existent_attribute
Error message:
Traceback (most recent call last):
File "example.py", line 18, in <module>
my_car.non_existent_attribute
AttributeError: 'Car' object has no attribute 'non_existent_attribute'
Solution: Make sure the attribute exists on the class and is properly spelled.
my_car.brand # This works, since 'brand' is an attribute of Car
Why it happens: The attribute doesn't exist or is misspelled.
How to prevent it: Double-check your code for typos and ensure that the attributes you want to access actually exist on the object.
What causes it: Trying to use a variable that hasn't been defined yet.
print(car_brand) # Before defining car_brand
Error message:
NameError: name 'car_brand' is not defined
Solution: Define the variable before using it.
my_car = Car("Toyota", "Corolla", 2020)
car_brand = my_car.brand
print(car_brand) # Now this works
Why it happens: The variable is not defined in the current scope.
How to prevent it: Define variables before using them or use a try/except
block to handle uninitialized variable errors.
What causes it: Passing an incorrect data type for a function argument.
my_car.year = "2020banana"
Error message:
Traceback (most recent call last):
File "example.py", line 10, in <module>
my_car.year = "2020banana"
TypeError: object doesn't support item assignment
Solution: Assign the correct data type for the attribute.
my_car.year = 2020
Why it happens: The data type you are trying to assign is not compatible with the expected data type of the attribute.
How to prevent it: Ensure that you are passing the correct data types for function arguments and attributes.