Download our e-book of Introduction To Python
Pallavi Dhotre
2 years ago
radious=10
def calculateArea():
area=3.14*radious**2 #without using class
print(area)
calculateArea()
class circle:
r=10 #variable declaration inside the class
def calculateArea(self):
area=3.14*self.r**2 #accessing the variable using self-keyword
print(area)
c=circle() #creating object
c.calculateArea() #calling function
314.0
class Demo:
def __init__(self): #python constructor example
a=40
b=a/5
print(b)
c=Demo()
200
class Demo:
def __init__(self,num1,num2): #parameterized constructor in python
self.number1=num1
self.number2=num2
def add(self):
return self.number1+self.number2
d=Demo(30,20)
sum=d.add()
print("Sum of two numbers: ",sum)
Addition of two numbers: 50
#constructor and destructor in python
class Demo:
number1=10
number2=20
def __int__(self): #default constructor in python
print("It is a default constructor")
def __init__(self,num1,num2): #parameterized constructors in python
self.number1=num1
self.number2=num2
def add(self):
return self.number1+self.number2
def __del__(self): #destructor in python
print("It is a destructor")
d=Demo(30,20)
sum=d.add()
print("Sum of two numbers: ",sum)
print("End of the program")
Sum of two numbers: 50
End of the program
It is a destructor
class Demo:
number1=10
number2=20
def __int__(self): #default constructor in python
print("It is a default constructor")
def __init__(self,num1,num2): #parameterized constructors in python
self.number1=num1
self.number2=num2
def add(self):
return self.number1+self.number2
d=Demo(30,20)
sum=d.add()
print("Sum of two numbers: ",sum)
Sum of two numbers: 50
#constructor overloading in python / multiple constructors in python
class Demo:
def __init__(self, *args):
#more than one argument then multiplication
if len(args)>1:
self.result=1
for i in args:
self.result *=i
#if the argument is a string then concat with hi
elif isinstance(args[0],str):
self.result= 'hi '+args[0]
# if the argument is float the print square of a number
elif isinstance(args[0],float):
self.result =args[0]*args[0]
d1=Demo(2,3,4,5)
print("Multiplication of the list is ",d1.result)
d2=Demo("InsideAIML")
print("String concatenation is ",d2.result)
d3=Demo(2.5)
print("The Square of the float is ",d3.result)
Multiplication of the list is 120
String concatenation is hi InsideAIML
The Square of the float is 6.25