A class is a blueprint for creating multiple objects. In Python, we define a class using the class
keyword followed by its name. Inside the class, we can define methods (functions associated with the class) and attributes (variables associated with each instance of the class).
class MyClass:
# Attributes are defined as variables inside the class
some_attribute = 0
def __init__(self, attribute_value):
self.some_attribute = attribute_value
def my_method(self):
print("Hello from my method!")
To create an object (instance) of the class, we use the class_name()
syntax and assign it to a variable.
my_object = MyClass(42)
You can access attributes using dot notation:
print(my_object.some_attribute) # Outputs: 42
Let's create a simple Rectangle
class that calculates the area of a rectangle based on its width and height.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
# Create a new rectangle and calculate its area
rectangle = Rectangle(5, 10)
print(rectangle.calculate_area()) # Outputs: 50
What causes it: Misspelling a class or method name when trying to use it.
# Bad code example that triggers the error
print(MyClas.calculate_area()) # Incorrect class name
Error message:
Traceback (most recent call last):
File "example.py", line 10, in <module>
print(MyClas.calculate_area())
NameError: name 'MyClas' is not defined
Solution: Ensure the class and method names are spelled correctly.
Why it happens: Python does not recognize undefined identifiers, causing a NameError
.
How to prevent it: Double-check your code for typos in class and method names.
What causes it: Attempting to call a method without providing the required object (instance).
# Bad code example that triggers the error
Rectangle.calculate_area() # Incorrect usage of the method
Error message:
TypeError: calculate_area() missing 1 required positional argument: 'self'
Solution: Always call methods on an instance (object) created from the class.
Why it happens: Python requires the self
parameter to access the instance attributes and methods inside a method definition.
How to prevent it: Use the correct syntax: instance_name.method_name()
.
self.__private_attribute
for private attributes).__init__
method).NameError
and TypeError
, and know how to fix them.