Octavian Hubbabuba
Octavian Hubbabuba

Reputation: 13

How do I run a random method from a class?

For example, how can I randomly use one of the four functions (within the class) listed below?

import random

class Calculate():
    def HI_1(x, y):
        return x + y
    def HI_2(x, y):
        return x - y
    def HI_3(x, y):
        return x * y
    def HI_4(x, y):
        return x/y


a = random.randint(1, 4)
b = 'HI_' + str(a)

p = Calculate.b(15, 7)
print(p)

My attempt to do so came with an error. Why did I get this error, and how can I do this?

Upvotes: 1

Views: 134

Answers (3)

Olivier Melançon
Olivier Melançon

Reputation: 22324

First, your methods should either be static or have self as first argument. Once that is fixed, you could use random.choice instead to choose the method out of a list. This has the advantage of not depending on the methods' names.

import random

class Calculate:
    @staticmethod
    def add(x, y):
        return x + y

    @staticmethod
    def sub(x, y):
        return x - y

    @staticmethod
    def mult(x, y):
        return x * y

    @staticmethod
    def div(x, y):
        return x/y

    @classmethod
    def random_op(cls, x, y):
        return random.choice([
            cls.add,
            cls.sub,
            cls.mult,
            cls.div
        ])(x, y)

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 244202

You can use getattr(), in addition your methods must be declared as staticmethod:

import random

class Calculate():
    @staticmethod
    def HI_1(x, y):
        return x + y

    @staticmethod
    def HI_2(x, y):
        return x - y

    @staticmethod
    def HI_3(x, y):
        return x * y

    @staticmethod
    def HI_4(x, y):
        return x/y


a = random.randint(1, 4)
b = 'HI_' + str(a)
p = getattr(Calculate, b)(15, 7)
print(b, p)

Upvotes: 1

Primusa
Primusa

Reputation: 13498

b is still a string. You need to evaluate it into an expression:

a = random.randint(1, 4)
b = 'HI_' + str(a)
func = eval("Calculate.{}".format(b))
func(15, 7)

Note you shouldn't be using eval() on any string that is a user input because it can lead to security vulnerabilities.

Upvotes: 1

Related Questions