Home > Back-end >  Why do I keep getting NameError: name is not defined
Why do I keep getting NameError: name is not defined

Time:01-27

I'm a noob to coding and just began my question. I started with python OOP and I ran into some trouble.

class Multidiv:
    def __init__(self, mulitple):
        self.mulitple = mulitple

    def mulitple(self, x, y):
        return x * y
    
    def divide(self, x, y):
        pass


math = Multidiv(mulitple, 10, 5)
print(math)

I keep getting a nameError and I don't understand why. Please help.

CodePudding user response:

there's a lot of mess in your code.. I suggest you get back to reading documentation/watching videos. for starter - mulitple is not defined. secondly, you're sending 10 and 5 but ignoring them in the init function. they won't get into to mulitple function.

you can do what you're trying to achieve like this:

class Multidiv:
    def __init__(self, mulitple):
        self.action = mulitple #save the string name as a member of the object.

    def mulitple(self, x, y):
        return x * y

    def divide(self, x, y):
        pass

math = Multidiv('mulitple') #pass the action name with qoutes as string, otherwise it won't be recognized.
actual_action = getattr(math, math.action) # use builtin function getattr to get the actual wanted method out of the object. (you can read about getattr online)
print(actual_action(10, 5)) call the actual action with the parameters you wish to calculate
  •  Tags:  
  • Related