Classes

Since Python is a object oriented programming language then you can use things like classes to define a object, a class is a bunch of methods that act on the data that is stored within the class itself. You can store data within the class, but unlike c++/java/c# etc, there is no private/public/protected, everything is public accessible.

In the example below, the class constructor is called (__init__ method) and the first parameter is the class object itself, which is why it is there and for many reasons why it is called self as a variable name.

 
#  self means the object itself.
 
class mysimpleclass :
        __myvar = 0
        def __init__(self,value = 0) :
                self.__myvar = value
 
        def printValue(self) :
                print self.__myvar
 
simple = mysimpleclass(5)
simple.printValue()

the printValue method just does that, it will print the value that is sorted within the class object and here is the output

5

if you did not put in the self in the example above for printing out the class object variable __myvar as below

class mysimpleclass ....
       ....
       def printValue() :
            print __myvar

the error would be

NameError: global name '_mysimpleclass__myvar' is not defined

because the interrupter is looking for a global variable and not a variable attached to that object.

Leave a Reply

Your email address will not be published. Required fields are marked *