Class and Object in Python Tutorial

Class and Object in Python

In this Tutorial we can learn how to create a class and how to access the property and how to initialize a value at runtime or command line argument using sys module and how to create function initialize data and call it.

As we know that Python is Object Oriented Programming Language. So it also supported class and object where class is used to grouping the data and using object we can access that data or property.

  1. Class is a blueprint or template of an object.
  2. Class is a group of objects which have same state and behaviour.

In Python class is a keyword that is used to decare a class followed by class name.

For Example:

    
    class Test:
        pass
    

In above example class is a keyword and Test is name of class. We can use pass keyword when we dont have anything in class.

For Example:

    class Test:
        x = 10
    
    h = Test()
    print(h.x)
   

Output is : 10

In above example we have a instance variable and we can access through object. So here h is an object using that we can access instance variable.

For Example:

    class Test:

        def __init__(self,x):
            self.x=x


h=Test(12)
print(h.x)
   

Output is : 12

In above example we can initialize a variable through init function.Init function is invoked when object is created.And self is a function parameter that is used to bind attributes with the given arguments.

For Example:

    import sys
    class Test:
    
        def __init__(self,x):
            self.x=x
            
    # sys.argv[1] where we can pass index and get value from particular position.
    i=sys.argv[1]
    
    h=Test(i)
    print(h.x)
   

Output is : 12

..\Python_Code> python hello.py 12

In above example sys is a module that we need to import and using sys module we can take argument at runtime through argv type of array based on index.

For Example:

    
    class Test:

        def add(self, x, y):
            print(x + y)

        def sub(self, x, y):
            print(x - y)

        def mul(self, x, y):
            print(x * y)

        def div(self, x, y):
            print(x / y)


h = Test()
h.add(1, 1)
h.sub(1, 1)
h.mul(1, 1)
h.div(1, 1)
    

Output is :

2

0

1

1.0

In above tutorial we create 4 different function to perform calculation like add(), sub(), mul() and div(). We can use def keyword to crate a function.

No comments: