How to Access Class Variable in Python

In Python, you can access a class variable using various methods.

The following examples show how to access a class variable in Python.

Accessing Class Variable within Class

We can use the self parameter to access a class variable within the class.

Suppose we have the following class:

# Create class
class Employee:
    emp_count = 100

    def print_emp(self):
        print(self.emp_count)

# Create an instance of Employee
emp = Employee()

# Call the print_emp method
emp.print_emp()

Output: 👇️

100

In this example, we access the class variable within the class using the self parameter.

Accessing Class Variable Outside Class

We can use the class name or an instance of the class to access a class variable outside the class.

Suppose we have the same class as above.

We can use the following code to access the class variable outside the class:

# Create class
class Employee:
    emp_count = 100

# Accessing class variable using the class name
print(Employee.emp_count)

# Accessing class variable using an instance of the class
emp = Employee()
print(emp.emp_count)

Output: 👇️

100
100

In this example, we access the class variable using the class name and also using an instance of the class.