Python Classes are just a group of data and/or functions. Classes though complicate the appearance of code, it can be used to put relatives together i.e. put all data and functions pertaining to a specific task under a single umbrella.
Data that is inside a class is called as an object. I.e a variable or a function of a class are the objects of that class.
- Example: create a class called “my_class” with two variables
- Example: create a class called “my_class” with two variables and a function
- Example: create a class called “my_class” with two variables and a function that accepts arguements
Example: create a class called “my_class” with two variables
>>> class my_class: ... var1 = "abc" ... var2 = "def" ... >>> my_inv = my_class() >>> print my_inv.var1 abc >>> print my_inv.var2 def >>>
In the above example, a class is defined with two variables in it. And, to be able to use a class, an instance has to be created first, which is in turn is used to reference its members. In the above example, my_env is an instance to the class my_class() and its members are referenced as m_inv.var1 where in, var1 is a member of my_class()
Example: create a class called “my_class” with two variables and a function
>>> class my_class: ... var1 = "abc" ... var2 = "def" ... def my_function(ref): ... print "the val1 is %s and the val2 is %s" % (ref.var1, ref.var2) ... >>> my_inv = my_class() >>> my_inv.my_function() the val1 is abc and the val2 is def >>>
In the above example, var1 and var2 are defined. A function my_function() is used to print the two variables var1 and var2 in a statement. However, When a function is defined inside a class, the function cannot accept the variables directly as parameters. We have to pass another parameter as an arguement to my_function and reference the two variables var1 and var2.
In the above example, they are referenced as ref.var1 and ref.var2.
Example: create a class called “my_class” with two variables and a function with arguements
>>> class my_class: ... def __init__(self, name, age): ... self.name = name ... self.age = age ... def test(abc): ... print "NAME: %s, AGE: %s" % (abc.name,abc.age) ... >>> my_inv = my_class("vijay","22") >>> my_inv.test() NAME: vijay, AGE: 22 >>>
In the above example, similar to the previous one, two arguements name and age are passed to the test() function to be printed in a statement. abc is the parameter used to reference them. However, the arguements name and age are not defined in the class, since it has to be passed at the time of function call.
For this to work, __init__() function has to be used. The first parameter ‘self’ of the __init__() function, is not passed at the time of function call. However it is used to reference the other arguements passed as arguements, which are name and age. Thus the self parameter is a reference to the class itself.