Python attributes and methods

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

Attributes

Attributes are variables that hold data about the object. They can be of any data type (e.g., string, integer, list) and are usually initialized within the __init__ method (also known as the constructor) of a class.

Types of Attributes

Instance Attributes: Specific to each object instance and defined within the __init__ method.

Class Attributes: Shared across all class instances and 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 defined within a class that describe the behavior of an object. They allow objects to perform actions and can interact with or modify the object’s attributes.

Types of Methods

Instance Methods: Operate on instance attributes and are defined with self as the first parameter.

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

Static Methods: Do not modify class or instance attributes, usually defined with @staticmethod decorator, and don’t 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