Class Vs Instance Variables in Python

05 min read

Instances of a class are created by calling a class object as a function. This first creates a new instance by calling the static method __new__() which is rarely defined by the user, but implemented a part of the object. This, in turn, calls the __init__()method of the class, which is almost always defined by a user to initialise the contents of an instance. Internally, instances are implemented using a dictionary that's accessible as the instance's __dict__ attribute. 

Whenever the attributes of an instance are modified, the changes are made in the instance's local dictionary. Within methods defined in the class, attributes are changed through assignment to self variable. In addition to this, new attributes can be added to an instance at any point in time.

It is important to note that a class statement does not create any instances of a class (no accounts are actually created). Rather, a class defines a set of attributes shared by all the instances that will be created later. In this sense, you might think of it as a blueprint that is used to create instances of an object.

The following example will help you understand better about the implementation of class variables and instances,

class girl:                                                         # a class is declared with a name 'girl'
      gender = 'female'                                # under the logic, all girls are females, gender is directly declared in the class. This gender is a class variable.
      def __init__(self, name):
                     self.name = name                # This is an Instance variable
r = girl('Sandy')
print(r.gender)                                        # returns as 'female'       class variable is being called and printed here.

    

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error