Attributes and Methods in Class
In Python, attributes and methods define the properties and behaviors of an object in a class. Attributes store data about the object, while methods define actions that can be performed on it.
What are Attributes?
Attributes in a class are variables that store information about an object. They are defined inside a class and can be accessed using the object of the class.
What are Methods?
Methods in a class are functions that perform specific operations on objects. They can modify attributes, perform calculations, or return information about the object.
Examples
1. Defining and Accessing Attributes
In this example, we create a class Car
with two attributes: brand
and year
. We then create an object and access its attributes.
We define the attributes inside the constructor method __init__
, which initializes the object when it’s created.
class Car:
def __init__(self, brand, year):
# Assigning attributes to the object
self.brand = brand
self.year = year
# Creating an object of the class
car1 = Car("Toyota", 2022)
# Accessing attributes
print("Car Brand:", car1.brand)
print("Manufacturing Year:", car1.year)
Output:
Car Brand: Toyota
Manufacturing Year: 2022
Here, self.brand
and self.year
store the values passed when creating the object. We then access these attributes using car1.brand
and car1.year
.
2. Using Methods to Modify Attributes
We now add a method to update the year
attribute. Methods allow us to change or manipulate object data.
The method update_year
takes a new year and updates the year
attribute of the object.
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
# Method to update the manufacturing year
def update_year(self, new_year):
self.year = new_year
# Creating an object
car1 = Car("Honda", 2020)
# Updating the year
car1.update_year(2023)
# Printing updated value
print("Updated Manufacturing Year:", car1.year)
Output:
Updated Manufacturing Year: 2023
The method update_year
changes the value of self.year
. When called with car1.update_year(2023)
, the year
is updated to 2023.
3. Instance Methods vs Class Methods
Instance methods operate on individual objects, while class methods affect the class itself. We use @classmethod
to define class methods.
In this example, total_cars
is a class attribute, and we use a class method get_total_cars
to access it.
class Car:
total_cars = 0 # Class attribute
def __init__(self, brand, year):
self.brand = brand
self.year = year
Car.total_cars += 1 # Increments total cars each time an object is created
@classmethod
def get_total_cars(cls):
return cls.total_cars
# Creating car objects
car1 = Car("Ford", 2019)
car2 = Car("BMW", 2021)
# Accessing class method
print("Total Cars Created:", Car.get_total_cars())
Output:
Total Cars Created: 2
Since total_cars
belongs to the class, every new object increases its value. The class method get_total_cars
returns the current count.
4. Handling Errors in Attribute Access
If we try to access an attribute that does not exist, Python raises an AttributeError
. We can handle this using getattr
built-in function.
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
# Creating an object
car1 = Car("Tesla", 2022)
try:
# Attempting to access a non-existent attribute
print(car1.color)
except AttributeError:
print("Error: The 'color' attribute does not exist in the object.")
# Using getattr safely
print("Color (default value used):", getattr(car1, "color", "Unknown"))
Output:
Error: The 'color' attribute does not exist in the object.
Color (default value used): Unknown
Accessing car1.color
causes an AttributeError
since it wasn’t defined. Using getattr
with a default value avoids this error.