Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để tạo một lớp thực hiện các phép toán trên máy tính

Khi cần tạo một lớp thực hiện các phép tính trên máy tính, phương pháp hướng đối tượng được sử dụng. Ở đây, một lớp được định nghĩa và các thuộc tính được định nghĩa. Các hàm được định nghĩa trong lớp thực hiện các hoạt động nhất định. Một thể hiện của lớp được tạo và các hàm được sử dụng để thực hiện các phép tính trên máy tính.

Dưới đây là một minh chứng cho điều tương tự -

Ví dụ

class calculator_implementation():
   def __init__(self,in_1,in_2):
      self.a=in_1
      self.b=in_2
   def add_vals(self):
      return self.a+self.b
   def multiply_vals(self):
      return self.a*self.b
   def divide_vals(self):
      return self.a/self.b
   def subtract_vals(self):
      return self.a-self.b
input_1 = int(input("Enter the first number: "))
input_2 = int(input("Enter the second number: "))
print("The entered first and second numbers are : ")
print(input_1, input_2)
my_instance = calculator_implementation(input_1,input_2)
choice=1
while choice!=0:
   print("0. Exit")
   print("1. Addition")
   print("2. Subtraction")
   print("3. Multiplication")
   print("4. Division")
   choice=int(input("Enter your choice... "))
   if choice==1:
      print("The computed addition result is : ",my_instance.add_vals())
   elif choice==2:
      print("The computed subtraction result is : ",my_instance.subtract_vals())
   elif choice==3:
      print("The computed product result is : ",my_instance.multiply_vals())
   elif choice==4:
      print("The computed division result is : ",round(my_instance.divide_vals(),2))
   elif choice==0:
      print("Exit")
   else:
      print("Sorry, invalid choice!")
print()

Đầu ra

Enter the first number: 70
Enter the second number: 2
The entered first and second numbers are :
70 2
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 1
The computed addition result is : 72
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 2
The computed subtraction result is : 68
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 3
The computed product result is : 140
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 4
The computed division result is : 35.0
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 0
Exit

Giải thích

  • Một lớp có tên là lớp ‘Calculator_implementation’ được xác định, có các chức năng như ‘add_vals’, ‘subtract_vals’, ‘multiple_vals’ và ‘split_vals’.
  • Chúng được sử dụng để thực hiện các phép tính trên máy tính như cộng, trừ, nhân và chia tương ứng.
  • Một phiên bản của lớp này đã được tạo.
  • Giá trị của hai số được nhập và các phép toán được thực hiện trên đó.
  • Thông báo và đầu ra có liên quan được hiển thị trên bảng điều khiển.