Class in Python

Class is a user defined datatype in which the user can define his/her own variables and functions. The syntax of the class is:-

class “Name”(“parent_class”):

statement 1

statement 2

Initially we use object as the parent class. In class we can declare multiple member functions. But the member functions must have a parameter a self. This is similar to the keyword this in C++.

class Add(object):

def sum(self, a, b):

return self.a+self.b

x = add(2,3)

print(“The sum is %d” %x.sum())

Output:-

The sum is 5

Inheritance:-

Inheritance can be done by replacing the name of the object class as a user defined class.

class A(object):

def a(self, aname):

self.aname = aname

def ret_a(self):

return self.aname

class B(A):

def b(self, bname):

self.bname = bname

def ret_b(self):

return self.bname

x = A(“Chandru”)

y = B(“Python”)

print(“Name in class A %s” % y.aname)

print(“Name in class B %s” % y.bname)

Output:-

Name in class A Chandru

Name in class B Python

Multiple classes:-

Multiple class can be declared by adding the parent class name in the paranthesis of the class.

class C(Object, A , B):

statement_1

statement_2

Leave a comment