Python Class and Instance Objects

What is class in python ?

  • Class is a blueprint or prototype that bundling data and functionality together.
  • class is used to define the new type. once defined, this new type can be used to create the objects of that type.
  • Each class instance can have attributes attached to it for maintaining its state.
  • Python’s class mechanism adds minimum of new syntax and semantics classes.

Class General Syntax:

class ClassName:
    statement - 1
    .
    .
    statement - N

Class Objects

  • Class objects support two kinds of operations: attribute references and instantiation.
  • Below Syntax is used for all attribute references in Python.
  • object_name.attribute_name
    
    #!/usr/bin/pyhton                                                               
                                                                                    
    class TestClass:                                                                
        """Test Class"""                                                            
        variable1 = 100;                                                            
        def show_message(self):                                                     
            return "Welcom to python class!";      
                                     
    # attribute references                                                                                
    print TestClass.variable1;                                                      
    print TestClass.show_message;                                                   
    print TestClass.__doc__;      
    
    Output:
    $ python test_class.py
    100
    <unbound method TestClass.show_message>
    Test Class
    
  • Function notation is used for class instantiation in python.
    instance_name = TestClass()
    
    #!/usr/bin/pyhton                                                               
                                                                                    
    class TestClass:                                                                
        """Test Class"""                                                            
        variable1 = 100;                                                            
        def show_message(self):                                                     
            return "Welcome to python class!";                                      
                                                                                    
                                                                                    
    obj = TestClass();                                                              
    print obj.variable1;                                                            
    print obj.show_message();                                                       
    print obj.__doc__;     
    
    Output;
    $ python test_class.py
    100
    Welcome to python class!
    Test Class
    
    creates a new instance of the class and assigns this object to the local variable 'instance_name'.
  • Instantiation operation (“calling” a class object) creates an empty object.

init method in python class

  • class may define a special method named __init__() to create objects with instances customized to a specific initial state.
    def __init__(self):
        self.data = []
    
  • class instantiation automatically invokes __init__() for the newly-created class instance.
  • __init__() method may have arguments, arguments given to the class instantiation operator are passed on to __init__().
    #!/usr/bin/pyhton                                                               
                                                                                    
    class TestClass:                                                                
        """Test Class"""                                                            
        variable1 = 100;                                                            
        def __init__(self, msg):                                                    
            self.msg = msg;                                                         
                                                                                    
        def show_message(self):                                                     
            return self.msg;                                                        
                                                                                    
                                                                                    
    obj = TestClass("Welcome to python class!");                                    
    print obj.variable1;                                                            
    print obj.show_message();                                                       
    print obj.__doc__;     
    
    Output:
    $ python test_class.py
    100
    Welcome to python class!
    Test Class
    
  • There are two kinds of valid attribute names: data attributes and methods.
    Data attributes correspond to “instance variables" and A method is a function that belongs to an object.

Method objects in python

#!/usr/bin/pyhton                                                               
                                                                                
class TestClass:                                                                
    """Test Class"""                                                            
    variable1 = 100;                                                            
    def __init__(self, msg):                                                    
        self.msg = msg;                                                         
                                                                                
    def show_message(self):                                                     
        return self.msg;                                                        
                                                                                
                                                                                
obj = TestClass("Welcome to python class!");                                    
sm = obj.show_message;                                                          
print sm();       
Output:
Welcome to python class!
here obj.show_message is the method object. sm stores the method object and can be called at later time.

Calling function with first argument as instance object

Calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument
#!/usr/bin/pyhton                                                               
                                                                                
class TestClass:                                                                
    """Test Class"""                                                            
    variable1 = 100;                                                            
    def __init__(self, msg):                                                    
        self.msg = msg;                                                         
                                                                                
    def show_message(self):                                                     
        return self.msg;                                                                                                                                       
                                                                                
obj = TestClass("Welcome to python class!");                                    
print TestClass.show_message(obj);     
here obj.show_message() is equivalent to TestClass.show_message(obj).

Class variables and instance variables

Class variable data shared by all instances and instance variable data unique to each instance.
#!/usr/bin/pyhton                                                               
                                                                                
class TestClass:                                                                
    """Test Class"""                                                            
    variable1 = 100; # class variable                                           
    def __init__(self, msg):                                                    
        self.msg = msg; # instance variable                                     
                                                                                
                                                                                
obj = TestClass("Instance object1");                                            
obj1 = TestClass("Instance object2");                                           
                                                                                
print "obj1 - variable1: ", obj.variable1, " and msg: ", obj.msg;               
print "obj2 -  variable2: ", obj1.variable1, " and msg: ", obj1.msg;      
Output:
$ python test_class.py 
obj1 - variable1:  100  and msg:  Instance object1
obj2 -  variable2:  100  and msg:  Instance object2

Class variable holding all instances data

Class variable 'instances' stores all the instances data together.
#!/usr/bin/pyhton                                                               
                                                                                
class TestClass:                                                                
    """Test Class"""                                                            
    instances = []; # class variable                                            
    def __init__(self, msg, ins):                                               
        self.msg = msg; # instance variable                                     
        self.instances.append(ins);                                             
                                                                                
                                                                                
obj = TestClass("Instance object1", "instance 1");                              
obj1 = TestClass("Instance object2", "instance 2");                             
print "obj1 - instances: ", obj.instances, " and msg: ", obj.msg;               
print "obj2 -  instances: ", obj1.instances, " and msg: ", obj1.msg;            
Output:
$ python test_class.py 
obj1 - instances:  ['instance 1', 'instance 2']  and msg:  Instance object1
obj2 -  instances:  ['instance 1', 'instance 2']  and msg:  Instance object2

Class methods - defined function outside the class

#!/usr/bin/pyhton                                                               
                                                                                
# Function defined outside the class                                            
def show_message(self):                                                         
    return self.msg;                                                            
                                                                                
class TestClass:                                                                
    """Test Class"""                                                            
    def __init__(self, msg):                                                    
        self.msg = msg;                                                         
                                                                                
    def get_length(self):                                                       
        return len(self.msg);                                                   
                                                                                
    sm = show_message                                                           
    gl = get_length                                                             
                                                                                
obj = TestClass("Instance object");                                             
obj1 = TestClass("Instance object 1");                                          
print "obj1 - msg length: ", obj.gl(), " and msg: ", obj.sm();                  
print "obj2 -  msg length: ", obj1.gl(), " and msg: ", obj1.sm();               
Output:
$ python test_class.py 
obj1 - msg length:  15  and msg:  Instance object
obj2 -  msg length:  17  and msg:  Instance object 1

Method may call another instance methods

#!/usr/bin/pyhton                                                               
                                                                                
class TestClass:                                                                
    """Test Class"""                                                            
    def __init__(self, msg):                                                    
        self.msg = msg;                                                         
                                                                                
    def get_length(self):                                                       
        return len(self.msg);                                                   
                                                                                
    def show_message(self):                                                     
        return self.msg + "length: " + str(self.get_length());                  
                                                                                
obj = TestClass("Instance object");                                             
obj1 = TestClass("Instance object 1");                                          
print "obj1 - msg: ", obj.show_message();                                       
print "obj2 - msg: ", obj1.show_message();                                      
Output:
$ python test_class.py 
obj1 - msg:  Instance objectlength: 15
obj2 - msg:  Instance object 1length: 17

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^