Class Variables Andmethds

UpComing SoftWare Training Demos

๐Ÿš€ *Playwright With AI Testing Demo In Telugu*
๐Ÿ—“๏ธ *Date:* 28 Oct2026, 08:00 PM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/3r
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/3w
๐Ÿ’ก *Course Content:*
https://www.vlrt.in/3c
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/3v

๐Ÿš€ *Gen AI Engineer (Production Focused)*
๐Ÿ—“๏ธ *Date:* 29th Oct 2026, 06:00PM 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

๐Ÿš€ *Vulnerability Management Training Demo*
๐Ÿ—“๏ธ *Date:* 28th Oct 2026, 10: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

Class Variables

Class variables are variables that are shared by all instances of a class. They are defined directly within the class but outside of any method. Unlike instance variables, which are unique to each object, a single copy of a class variable is shared among all objects of that class. They are useful for storing data that is common to all instances, such as constants or default values.

Example:

Consider a School class. All students in the school share the same school name. This can be stored as a class variable.

class School:
    # This is a class variable
    school_name = "Springfield Elementary"

    def __init__(self, student_name):
        self.student_name = student_name  # This is an instance variable

# Creating two student objects
student1 = School("Bart Simpson")
student2 = School("Lisa Simpson")

print(f"{student1.student_name} attends {student1.school_name}.")
print(f"{student2.student_name} attends {student2.school_name}.")

# You can also access the class variable directly from the class
print(School.school_name)

In this example, school_name is a class variable. Both student1 and student2 objects access the exact same value for school_name.


Methods

Methods are functions defined inside a class that describe the behaviors of an object. There are two main types of methods related to class and instance variables:

  1. Instance Methods: These are the most common type of method. They operate on an instance of a class and can access both instance and class variables. They always have self as their first parameter, which refers to the specific object the method is called on.
  2. Class Methods: These methods operate on the class itself, not on an instance. They are declared with the @classmethod decorator and take cls (short for class) as their first parameter, which refers to the class itself. They are often used to create factory methods or to modify class variables.

Example:

Let’s expand the School class with both types of methods.

class School:
    # Class variable
    school_name = "Springfield Elementary"
    total_students = 0

    def __init__(self, student_name):
        self.student_name = student_name
        School.total_students += 1  # Incrementing the class variable

    # Instance Method
    def get_student_info(self):
        return f"{self.student_name} is a student at {self.school_name}."

    # Class Method
    @classmethod
    def get_total_students(cls):
        return f"The total number of students is {cls.total_students}."

# Creating student objects
student1 = School("Bart Simpson")
student2 = School("Lisa Simpson")

# Calling the instance method
print(student1.get_student_info())

# Calling the class method using the class
print(School.get_total_students())

In this example, get_student_info is an instance method that uses self to access the specific student’s name. get_total_students is a class method that uses cls to access and report the shared total_students variable for the entire class.

This program demonstrates the use of class variables, instance variables, and different types of methods in Python. It creates a School class to manage student information and a total count of students.

Class and Instance Variables

  • school_name = "Springfield Elementary": This is a class variable. It’s defined directly inside the class and is shared by all objects created from the School class.
  • total_students = 0: This is also a class variable. It keeps a running count of all School objects created.
  • self.student_name = student_name: This is an instance variable. It’s created within the __init__ method and is unique to each individual student object (student1, student2, etc.).

Methods

  • __init__(self, student_name): This is the constructor method. It’s called automatically whenever a new School object is created. It initializes the unique student_name for that object and increments the shared total_students class variable.
  • get_student_info(self): This is an instance method. It uses the self parameter to access and return a string that includes both the unique student_name (an instance variable) and the shared school_name (a class variable) for a specific object.
  • get_total_students(cls): This is a class method, indicated by the @classmethod decorator. It takes cls (the class itself) as its first parameter instead of self (the instance). This method can only access and operate on class variables, such as cls.total_students. It’s called on the class itself (School.get_total_students()) rather than on an object.

Program Flow

  1. student1 = School("Bart Simpson"): A new School object is created. The __init__ method is called, setting student1.student_name to “Bart Simpson” and incrementing School.total_students to 1.
  2. student2 = School("Lisa Simpson"): Another School object is created. __init__ is called again, setting student2.student_name to “Lisa Simpson” and incrementing School.total_students to 2.
  3. print(student1.get_student_info()): The get_student_info instance method is called on the student1 object. It returns the string “Bart Simpson is a student at Springfield Elementary.”
  4. print(School.get_total_students()): The get_total_students class method is called on the School class. It returns the string “The total number of students is 2.”

Similar Posts

  • Instance Variables,methods

    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…

  • Sets in Python

    Sets in Python A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove items, but the elements themselves must be immutable (like numbers, strings, or tuples). Key Characteristics of Sets: Different Ways to Create Sets in Python Here are various methods to create sets in…

  • Python Installation Guide: Easy Steps for Windows, macOS, and Linux

    Installing Python is a straightforward process, and it can be done on various operating systems like Windows, macOS, and Linux. Below are step-by-step instructions for installing Python on each platform. 1. Installing Python on Windows Step 1: Download Python Step 2: Run the Installer Step 3: Verify Installation If Python is installed correctly, it will…

  • 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…

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Closure Functions in Python

    Closure Functions in Python A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope. Simple Example python def outer_function(x): # This is the enclosing scope def inner_function(y): # inner_function can access ‘x’ from outer_function’s scope return x + y return inner_function…

Leave a Reply

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