Creating class
Class keyword is used to create a class.
Syntax:
class classname(object):
“”” docstring”””
attributes
def__init __(self)
def method1(self)
In above syntax after class name object is written. It describes that from where the class is derived. Object is base class of all classes and here to write object is not compulsory.
The docstring describes the details about the class.it is documentation about the class. It is optional.
Attributes are the variables that contains the data.
__init__(self) is a special method that is used to initialize the variables. It is called constructor.
The init method is prefixed and suffixed by two underscore. It suggest that it is internal method and cannot be invoked explicitly. The self written as parameter suggest that it refers to current class instance.
This instance is stored in heap and the memory location is stored in self, by default. The instance contains variables called instance variables. Dot operator is used to refer the instance variable.
The methods that work on an object are called instance methods. Instance method use self as parameter. With use of self key word they can work on instance variables. Constructor is also refer as instance method.
To create an instance (object) following syntax is used.
Instancename = classname()
Example:
class emp:
def __init__(self):
self.id=1
self.name="abc"
def printdata(self):
print("Emp id is",self.id)
print("Emp name is",self.name)
e1=emp()
e1.printdata()
e2=emp()
e2.printdata()
In above code class emp has been created. Constructor is defined within that id and name initialised and printdata is instance method.
The statement,
e1=emp()
creates an instance e1 of class emp. Through above statement memory is allocated for instance of emp class and with use of e1 you can use the instance variable and instance methods of the emp class.
The self variable
‘self’ can be identified as keyword as it refers to attributes of current instance.
It refer to the instance of current class.
Self is used to refer all variables and methods of current class.
The self variable stores the memory location of current instance.
In above example when we write,
e1=emp()
memory is allocated to create instance of emp class and the address is assigned to e1. The memory address is internally assigned to self variable.
The self variable is used as, first parameter in constructor.
def __init__(self):
It is also used as first parameter in instance method.
def printdata(self):