Create a new class Math1 in Python
Create a New Python Class Math1
- Create a new class Math1
- Create a Constructor for Math1 class
- Define two instance varables num1, num2
- Write a method add(self) to add the numbers and return sum
- Create two objects obj1 and obj2, passing 10,20 and 40,60 values
- Call add() method with object1
- Call add() method with object 2
Create a New Class Math1 in Python
How To Create A Class Math1 to Add Two Numbers
- First of all we will dfine a class Math1 using 'class' keyword.
- Define a construcor that is __init__() method to initialize newly created objects.
- We will define two instance variables num1, num2 in the __init__() method.
- Three parameters are used in __init__(self, num1, num2)
- 'self' refers to the current object upon which the __init__() method is called.
- num1 and num2 are the instance variables of Math1 class.
- We will assign the values of parameters to the instance variables, so that both of the instance variables are initialized at the time of object creation (AKA instanitiation).
- Similarly, define another method add(self) to return the sum of the two instance variables.
- Now, the class code is ended here, now add some statements to main() at zero indentation level.
- Add the statements to create two objects, obj1 and obj2 with values 10,20 and 40,60 respectively.
- Call the add() method for the newly created objects of Math1 class.
- Hence the output of the program will display on the screen
Coding of the Program Math1 Class
Sum1 = 30 Sum2 = 100
Python Program with comments