Cara menggunakan class member variable python

In Object-oriented programming, when we design a class, we use instance variables and class variables.

In Class, attributes can be defined into two parts:

  • Instance variables: If the value of a variable varies from object to object, then such variables are called instance variables.
  • Class Variables: A class variable is a variable that is declared inside of class, but outside of any instance method or 
    Emma 10 ABC School
    Jessa 20 ABC School 
    9 method.

After reading this article, you’ll learn:

  • How to create and access class variables
  • Modify values of a class variables
  • Instance variable vs. class variables
  • Behaviour of a class variable in inheritance

Table of contents

What is an Class Variable in Python?

If the value of a variable is not varied from object to object, such types of variables are called class variables or static variables.

Class variables are shared by all instances of a class. Unlike instance variable, the value of a class variable is not varied from object to object,

In Python, Class variables are declared when a class is being constructed. They are not defined inside any methods of a class because of this only one copy of the static variable will be created and shared between all objects of the class.

For example, in Student class, we can have different instance variables such as name and roll number because each student’s name and roll number are different.

But, if we want to include the school name in the student class, we must use the class variable instead of an instance variable as the school name is the same for all students. So instead of maintaining the separate copy in each object, we can create a class variable that will hold the school name so all students (objects) can share it.

We can add any number of class variables in a class.

Cara menggunakan class member variable python
Cara menggunakan class member variable python
Understand Class Variables

Create Class Variables

A class variable is declared inside of class, but outside of any instance method or 

Emma 10 ABC School
Jessa 20 ABC School 
9 method.

By convention, typically it is placed right below the class header and before the constructor method and other methods.

Example:

class Student:
    # Class variable
    school_name = 'ABC School '
    
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

# create first object
s1 = Student('Emma', 10)
print(s1.name, s1.roll_no, Student.school_name)
# access class variable

# create second object
s2 = Student('Jessa', 20)
# access class variable
print(s2.name, s2.roll_no, Student.school_name)

Output

Emma 10 ABC School
Jessa 20 ABC School 

In the above example, we created the class variable

class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')
1 and accessed it using the object and class name.

Note: Like regular variables, class variables can store data of any type. We can use Python list, Python tuple, and Python dictionary as a class variable.

Accessing Class Variables

We can access static variables either by class name or by object reference, but it is recommended to use the class name.

In Python, we can access the class variable in the following places

  • Access inside the constructor by using either
    class Student:
        # Class variable
        school_name = 'ABC School '
    
        # constructor
        def __init__(self, name):
            self.name = name
            # access class variable inside constructor using self
            print(self.school_name)
            # access using class name
            print(Student.school_name)
    
    # create Object
    s1 = Student('Emma')
    2 parameter or class name.
  • Access class variable inside instance method by using either self of class name
  • Access from outside of class by using either object reference or class name.

Example 1: Access Class Variable in the constructor

class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')

Output

ABC School 
ABC School

Example 2: Access Class Variable in Instance method and outside class

class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

    # Instance method
    def show(self):
        print('Inside instance method')
        # access using self
        print(self.name, self.roll_no, self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma', 10)
s1.show()

print('Outside class')
# access class variable outside class
# access using object reference
print(s1.school_name)

# access using class name
print(Student.school_name)

Output

Inside instance method
Emma 10 ABC School 
ABC School 

Outside class
ABC School 
ABC School 

In this example, we accessed the class variable

class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')
1 using class name and a
class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')
2 keyword inside a method.

Modify Class Variables

Generally, we assign value to a class variable inside the class declaration. However, we can change the value of the class variable either in the class or outside of class.

Note: We should change the class variable’s value using the class name only.

Example

class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

    # Instance method
    def show(self):
        print(self.name, self.roll_no, Student.school_name)

# create Object
s1 = Student('Emma', 10)
print('Before')
s1.show()

# Modify class variable
Student.school_name = 'XYZ School'
print('After')
s1.show()

Output:

Before
Emma 10 ABC School 

After
Emma 10 XYZ School

Note:

It is best practice to use a class name to change the value of a class variable. Because if we try to change the class variable’s value by using an object, a new instance variable is created for that particular object, which shadows the class variables.

Example:

class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

# create Objects
s1 = Student('Emma', 10)
s2 = Student('Jessa', 20)

print('Before')
print(s1.name, s1.roll_no, s1.school_name)
print(s2.name, s2.roll_no, s2.school_name)

# Modify class variable using object reference
s1.school_name = 'PQR School'
print('After')
print(s1.name, s1.roll_no, s1.school_name)
print(s2.name, s2.roll_no, s2.school_name)

Output:

Before
Emma 10 ABC School 
Jessa 20 ABC School 

After
Emma 10 PQR School
Jessa 20 ABC School 

A new instance variable is created for the s1 object, and this variable shadows the class variables. So always use the class name to modify the class variable.

Class Variable vs Instance variables

The following table shows the difference between the instance variable and the class variable.

In Python, properties can be defined into two parts:

  • Instance variables: Instance variable’s value varies from object to object. Instance variables are not shared by objects. Every object has its own copy of the instance attribute
  • Class Variables: A class variable is a variable that is declared inside of class, but outside of any instance method or 
    Emma 10 ABC School
    Jessa 20 ABC School 
    9 method. Class variables are shared by all instances of a class.

Read More: Instance variables in Python with Examples

Instance VariableClass VariableInstance variables are not shared by objects. Every object has its own copy of the instance attributeClass variables are shared by all instances.
Instance variables are declared inside the constructor i.e., the
Emma 10 ABC School
Jessa 20 ABC School 
9 method.Class variables are declared inside the class definition but outside any of the instance methods and constructors.It is gets created when an instance of the class is created.It is created when the program begins to execute.Changes made to these variables through one object will not reflect in another object.Changes made in the class variable will reflect in all objects.Class Variables vs. Instance Variables

Example:

Let’s see the example to create a class variable and instance variable.

Emma 10 ABC School
Jessa 20 ABC School 
0

Output:

Emma 10 ABC School
Jessa 20 ABC School 
1

Class Variables In Inheritance

As you know, only one copy of the class variable will be created and shared between all objects of that class.

When we use inheritance, all variables and methods of the base class are available to the child class. In such cases, We can also change the value of the parent class’s class variable in the child class.

We can use the parent class or child class name to change the value of a parent class’s class variable in the child class.

Example

Emma 10 ABC School
Jessa 20 ABC School 
2

Output

Emma 10 ABC School
Jessa 20 ABC School 
3

What if both child class and parent class has the same class variable name. In this case, the child class will not inherit the class variable of a base class. So it is recommended to create a separate class variable for child class instead of inheriting the base class variable.

Example:

Emma 10 ABC School
Jessa 20 ABC School 
4

Output:

Emma 10 ABC School
Jessa 20 ABC School 
5

Wrong Use of Class Variables

In Python, we should properly use the class variable because all objects share the same copy. Thus, if one of the objects modifies the value of a class variable, then all objects start referring to the fresh copy.

For example,

Example

Emma 10 ABC School
Jessa 20 ABC School 
6

Output

Emma 10 ABC School
Jessa 20 ABC School 
7

In the above example, the instance variable

class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')
7 is unique for each player. The class variable
class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')
8 and
class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')
9 can be accessed and modified by any object.

Because both objects modified the class variable, a new instance variable is created for that particular object with the same name as the class variable, which shadows the class variables.

In our case, for object

ABC School 
ABC School
0 new instance variable
ABC School 
ABC School
1 gets created, and for object
ABC School 
ABC School
2 new instance variable
class Student:
    # Class variable
    school_name = 'ABC School '

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')
9 gets created.

So when you try to access the class variable using the

ABC School 
ABC School
0 or
ABC School 
ABC School
2 object, it will not return the actual class variable value.

To avoid this, always modify the class variable value using the class name so that all objects gets the updated value. Like this