简体   繁体   中英

Pass a python operation in a function parameter

can you solve this for me? I want to

  • call the Main class and pass 2 number in it
  • and call the add or subtraction function.

I have tried this.
want result 8 but got this {}

class Main(object):
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

    def add(self):
        response = Main.main(self.num1 + self.num2)
        print(response)

    def subtraction(self):
        response = Main.main(self.num1 - self.num2)
        print(response)

    def main(self, **kwargs):
        try:
            result = kwargs
        except:
            return 'Invalid operation'

        return result


if __name__ == '__main__':
    Main(5, 3).add()

Instead of

def add(self):
    response = Main.main(self.num1 + self.num2)
    print(response)

def subtraction(self):
    response = Main.main(self.num1 - self.num2)
    print(response)

Try:

def add(self):
    response = self.num1 + self.num2
    print(response)

def subtraction(self):
    response = self.num1 - self.num2
    print(response)
class Main(object):
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

    def add(self):
        response = self.main(self.num1 + self.num2)
        print(response)

    def subtraction(self):
        response = self.main(self.num1 - self.num2)
        print(response)

    def main(self, result):
        try:
            result = result
        except:
            return 'Invalid operation'

        return result


if __name__ == '__main__':
    Main(5, 3).add()

What you are trying to do is impossible, the class has to first be instantiated before their methods can be called. You can't do both at the same time. Why do you even want to do that? If you really want to do it then this should work.

class Main(object):

    def __new__(cls, num1, num2, operator=None):
        print( {"add": num1 + num2,"subtrack": num1 - num2 }[operator] )

        return super().__new__(cls)

Main(1, 2, "add")
Main(1, 2, "subtrack")

You don't need to create a main function inside Main class.

class Main(object):
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

    def add(self):
        response = self.num1 + self.num2
        return response

    def subtraction(self):
        response = self.num1 - self.num2
        return response

Using above code Main(5, 3).add() will return 8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM