Skip to main content

Python #7-Class and Objects in Python

cont....
         of Python #6- Keyword in Python


What is Class ?
A class is a collections of objects.
It is also called as grouping of data and functions.

Syntax:

   class className():
       def methodName1(self):
            statement
       def methodaName(self):
             statement

Example:


 Explanation:

   As we know Python follows indentation. The spacing for the lines should be strictly followed to avoid any errors.

#line 1: It consists of the class name cname():

#line 2: def add(self):
               This line allows you to create a function or method in python.

Note Worthy: "self" is built in parameter constant which takes its own parameters if does not any parameters or arguments are supplied.

#line 3: It is the normal print statement which is inside the Add() function.

#line 4: def sub(self):
                This is again another method which print "Subtraction" ones this method is invoked.

#line 7: def main():
               Creating of main method which is used to access the class.
               As we know that in order to access a class we need to use the main method.

#line 8: c=cname()
                c is object which i created for the class cname().

#line 9: c.add()
               This line is used to call the add() inside the cname() class.

#line 10: c.sub()
                This line is used to call the sub() inside the cname() class.

#line 12: main()
                This line is used to call the main() method.

Note Worthy: In Python you need to call the main method to start .Like the above statement.
You can alos use like this to call the main()

eg: if _name_ == "_main_"
         main()


Come back to learn more from Tech Bird


Thanks and regards,
Tech bird

Comments