Why do I keep getting NameError: name is not defined

Why do I keep getting NameError: name is not defined

我是编码菜鸟,刚开始我的问题。我从 python OOP 开始,然后 运行 遇到了一些麻烦。

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)

我一直收到 nameError,我不明白为什么。请帮忙。

你的代码中有很多混乱。我建议你回去阅读 documentation/watching 视频。 对于初学者 - mulitple 未定义。 其次,您发送 10 和 5 但在 init 函数中忽略它们。他们不会进入多重功能。

您可以像这样实现您想要实现的目标:

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