Python Attributes and Methods

In Python, attributes and methods are key to defining the properties and behaviors of objects in a class.

Attributes

Attributes are variables that store data about the object. They can be any data type, such as string, integer, or list. They are usually set up in the __init__ method, which is also called the constructor, of a class.

Types of Attributes

Instance Attributes: These are specific to each object instance and are defined in the __init__ method.

Class Attributes: These are shared across all class instances and are defined outside any method within the class.

Example:


class Car:
    # Class attribute
    vehicle_type = "Car"

    def __init__(self, brand, color):
        # Instance attributes
        self.brand = brand
        self.color = color

create the Object


# Creating two objects of the Car class
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")

print(car1.brand)         # Output: Toyota
print(car2.color)         # Output: Blue
print(car1.vehicle_type)  # Output: Car (shared class attribute)

Methods

Methods are functions that belong to a class and explain how an object behaves. They enable objects to perform actions and can interact with or change the object’s attributes.

Types of Methods

Instance Methods: These work with instance attributes and are defined with self as the first parameter.

Class Methods: These work with class attributes and use the @classmethod decorator with cls as the first parameter.

Static Methods: These do not change class or instance attributes. They are usually defined with the @staticmethod decorator and do not take self or cls as a parameter.

Example


class Car:
    vehicle_type = "Car"  # Class attribute

    def __init__(self, brand, color):
        self.brand = brand  # Instance attribute
        self.color = color  # Instance attribute

    # Instance method
    def start(self):
        print(f"The {self.color} {self.brand} is starting.")

    # Class method
    @classmethod
    def change_vehicle_type(cls, new_type):
        cls.vehicle_type = new_type

    # Static method
    @staticmethod
    def is_motor_vehicle():
        return True

create a Object


# Creating an instance
my_car = Car("Tata", "White")

# Calling instance method
my_car.start()  # Output: The White Tata is starting.

# Calling class method
Car.change_vehicle_type("Electric Car")
print(Car.vehicle_type)  # Output: Electric Car

# Calling static method
print(Car.is_motor_vehicle())  # Output: True