Class and Object Variables

When we started this Chapter, we discussed how the wrapping of data and functionality is done in a Class that is initialized using an object. It's time to now talk about the "data" part in that statement. We have seen how to work on the "functionalities" using Methods. So, what are Class and Object variables? They are quite straightforward.

Class variables are the variables that belong to the Class and these can be used by any instances of the Class. There is only one copy of this variable, and a change in this variable is observed in all instances whenever it's put to use.

Object variables, on the other hand, are variables initialized by the objects individually. Every object has it's own copy of the variable and a change in them doesn't affect the entire Class. This is where self plays an important role.

We will learn more the implementation. You can use the white space on your Repl editor and RUN the code.

class Boys:

    sex = 'Male'

    def __init__(self,name):
        self.name = name
        print('Name is set to ' + self.name)
    def introduce(self):
        print('My name is ' + self.name + ' and my sex is ' + Boys.sex)

b = Boys('Alix')
b.introduce()

This outputs to:

Name is set to Alix
My name is Alix and my sex is Male

This is what happens when you don't pass the name as an argument:

b = Boys()

TypeErrorTraceback (most recent call last)
<ipython-input-19-3d9e2cd61354> in <module>()
----> 1 b = Boys()

TypeError: __init__() takes exactly 2 arguments (1 given)

As we can see in the code, we initialize an object b that is passed with the name Alix which is stored in the object variable name. Meanwhile, the class variable sex remains constant. Lets see another input to the code:

c = Boys('Casey')
c.introduce()

This would result in:

Name is set to Casey
My name is Casey and my sex is Male

Hence, the object variables keeps a different value for each object, whereas the class variable doesn't change.

results matching ""

    No results matching ""