Python Forum
How to pass a method as argument in an another method?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to pass a method as argument in an another method?
#1
Question 
I want to write a python calculator program that has different methods to add, subtract, multiply which takes 2 parameters. I need to have an execute method when passed with 3 parameters, should call respective method and perform the operation. How can I achieve that?

class calc():
    def __init__(self,a,b):
        self.a=a
        self.b=b
        
    def ex(self,fun):
        self.fun=fun
        if fun=="add":
            self.add()
    
    def add(self):
        return self.a+self.b
    def sub(self):
        return self.a-self.b
    def mul(self):
        return self.a*self.b
    def div (self):
        return self.a/self.b
    def execu(
obj1=calc()
obj1.ex("add",1,,2)
Reply


Messages In This Thread
How to pass a method as argument in an another method? - by anilanvesh - Sep-30-2021, 05:28 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Int.From_Bytes Method - Conversion of Non-Escaped Bytes Objects new_coder_231013 2 402 Apr-06-2024, 04:24 PM
Last Post: new_coder_231013
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 272 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  class definition and problem with a method HerrAyas 2 253 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  super() and order of running method in class inheritance akbarza 7 737 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  problem usage of static method akbarza 5 539 Feb-03-2024, 07:43 AM
Last Post: paul18fr
  Building a DoublyLinkedList in Python - - append method Drone4four 2 423 Jan-08-2024, 01:27 PM
Last Post: Drone4four
  How to pass encrypted pass to pyodbc script tester_V 0 857 Jul-27-2023, 12:40 AM
Last Post: tester_V
Information Best distribution method inovermyhead100 0 557 Jul-19-2023, 07:39 AM
Last Post: inovermyhead100
  method call help sollarriiii 6 1,155 Feb-21-2023, 03:19 AM
Last Post: noisefloor
  That compression method is not supported tester_V 9 3,505 Jan-31-2023, 07:05 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020