Classes in Python

A class is a collection of data and methods in a single unit. The __init__ method in Python becomes the constructor while the __str__ is the toString method. The self variable should be compared to the this pointer. Python does not support overloading but overloading can be simulated using named parameters of Python.

class Complex:
def __init__(self, rp=None, ip=None):
if(rp==None and ip==None):
self.r = 0
self.i = 0
elif(rp==None):
self.r=ip
self.rp=ip
elif(ip==None):
self.r=rp
self.i=rp
else:
self.r=rp
self.i=ip
def __str__(self):
if(self.i<0):
return str(self.r) + ” -i* ” + str(-self.i)
else:
return str(self.r) + ” +i* ” + str(self.i)

x = Complex(2)
print(x)
class in python

 

Leave a Reply