Instance Variables,methods

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

Instance Variables

Instance variables are variables defined within a class but outside of any method. They are unique to each instance (object) of a class. This means that if you create multiple objects from the same class, each object will have its own separate copy of the instance variables. They are used to store the state of an object.

Example:

Consider a Car class. Each car has its own unique color and speed. These properties can be represented as instance variables.

class Car:
    def __init__(self, color, speed):
        self.color = color  # This is an instance variable
        self.speed = speed  # This is an instance variable

# Creating two car objects
car1 = Car("red", 100)
car2 = Car("blue", 120)

print(f"Car 1 is {car1.color} and its speed is {car1.speed} km/h")
print(f"Car 2 is {car2.color} and its speed is {car2.speed} km/h")

In this example, color and speed are instance variables. car1 has color as “red” and speed as 100, while car2 has its own color as “blue” and speed as 120.


Methods

Methods are functions defined inside a class. They represent the behaviors or actions that an object can perform. Methods can access and modify the instance variables of the object they belong to. They typically have self as their first parameter, which refers to the instance of the object itself.

Example:

Using the same Car class, we can add a method called accelerate to change the car’s speed.

class Car:
    def __init__(self, color, speed):
        self.color = color
        self.speed = speed

    def accelerate(self, increment):  # This is a method
        self.speed += increment
        print(f"The {self.color} car is now accelerating. New speed is {self.speed} km/h")

# Creating a car object
my_car = Car("green", 80)

# Calling the accelerate method on the object
my_car.accelerate(20)
my_car.accelerate(10)

In this example, the accelerate method changes the speed instance variable of the my_car object. The self parameter is used to access the speed variable specific to my_car.

Declare instance variables

You can declare instance variables in a class using the self keyword, most commonly within the __init__ constructor method. They can also be declared in other methods or even outside the class after object creation.


1. Declaring in the __init__ Constructor

This is the most common and recommended way to declare instance variables. The __init__ method is automatically called when a new object is created, ensuring that every object has these variables from the start.

Example:

Python

class Dog:
    # The __init__ method is a constructor
    def __init__(self, name, age):
        self.name = name  # Declaring an instance variable
        self.age = age    # Declaring another instance variable

# Creating two different Dog objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

print(f"Dog 1's name is {dog1.name} and age is {dog1.age}.")
print(f"Dog 2's name is {dog2.name} and age is {dog2.age}.")

In this example, self.name and self.age are instance variables. Each Dog object, dog1 and dog2, has its own unique name and age values.


2. Declaring in Other Methods

You can also declare an instance variable inside any other method of the class. However, this is generally less common and can make your code harder to read, as the variable will only exist on an object if that specific method has been called.

Example:

Python

class User:
    def __init__(self, username):
        self.username = username

    def add_email(self, email):
        self.email = email  # Declaring the instance variable here

# Creating a User object
user1 = User("john_doe")

# The 'email' instance variable doesn't exist yet
# print(user1.email)  # This would cause an error!

# Calling the method to declare the variable
user1.add_email("john@example.com")
print(user1.email)

Here, self.email is only created and available after the add_email method is called.


3. Declaring Dynamically Outside the Class

You can add an instance variable to an object at any point after it’s created, using the object name followed by the dot operator. This is also not a common practice as it can lead to inconsistent objects.

Example:

Python

class Student:
    def __init__(self, name):
        self.name = name

# Creating a Student object
student1 = Student("Alice")

# Dynamically adding a new instance variable
student1.grade = "A"

print(f"{student1.name}'s grade is {student1.grade}.")

Similar Posts

  • Decorators in Python

    Decorators in Python A decorator is a function that modifies the behavior of another function without permanently modifying it. Decorators are a powerful tool that use closure functions. Basic Concept A decorator: Simple Example python def simple_decorator(func): def wrapper(): print(“Something is happening before the function is called.”) func() print(“Something is happening after the function is…

  • Operator Overloading

    Operator Overloading in Python with Simple Examples Operator overloading allows you to define how Python operators (like +, -, *, etc.) work with your custom classes. This makes your objects behave more like built-in types. 1. What is Operator Overloading? 2. Basic Syntax python class ClassName: def __special_method__(self, other): # Define custom behavior 3. Common Operator Overloading Methods Operator…

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • Indexing and Slicing for Writing (Modifying) Lists in Python

    Indexing and Slicing for Writing (Modifying) Lists in Python Indexing and slicing aren’t just for reading lists – they’re powerful tools for modifying lists as well. Let’s explore how to use them to change list contents with detailed examples. 1. Modifying Single Elements (Indexing for Writing) You can directly assign new values to specific indices. Example 1:…

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

Leave a Reply

Your email address will not be published. Required fields are marked *