Saturday, 10 August 2019

Class and Objects in Python

       Class And Objects In Python

Class

A class is a collection of methods and attributes.It is also known as blueprint of object.It is defined by using keyword *class*.
A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package.

How to create a class 

      class classname :
     
Example -

class firstclass :
    x = 1 
                

Object

Object is the copy of class.It is also called as instance of class.
Object is simply a collection of data (variables) and methods (functions) that act on those data .

Example -
An object named p1 is made for class firstclass

p1 = firstclass()
print(p1.x) 
                          

__init__() function

It is a special attribute *__init__()* function  that begins with underscore underscore init underscore underscore.
All classes have a function called __init__() ,which is always executed when the class is being intiated.
Use the __init__()function to assign value to object properties or other operations that are necessary to do when the object is being created.

Example -


class firstclass:
    def __init__(self ,name , age):
        self.name = name
        self.age = age


Save the above code as class_and_objects_in_python.py and run it with command python class_and_objects_in_python.py




0 comments:

Post a Comment

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel