首页 > 解决方案 > NameError on a function while calling for it in another function of a class

问题描述

I developed some code for a problem on leetcode.com. There was a class and a function and I added another function matchingBrackets. Yet, when I make the code run I have a NameError on this function. Indeed, it seems it is not defined.

class Solution:

    def matchingBrackets(self, s:str) -> bool:
        lefts = ['(','{','[']
        rights = [')',']','}']
        if s[0] in lefts:
            function(s[1:],type)
        elif s[0] in rights:
            if s[0] == bracket:
                return True
            else:
                return False
        else:
            print("different from brackets")
            s = s[1:]

    def isValid(self, s: str) -> bool:

        return matchingBrackets(s[1:],bracket)

When running it the code on leetcode console, it returns:

NameError: name 'matchingBrackets' is not defined
Line 19 in isValid (Solution.py)
Line 30 in __helper__ (Solution.py)
Line 44 in _driver (Solution.py)
Line 55 in <module> (Solution.py)

标签: python-3.xnameerror

解决方案


我认为有几个问题。

当您提到在同一个类中定义的方法时def method(self, arg1, arg2):,您需要进一步使用该方法,就self.method(arg1, arg2)好像您在同一个类中使用它一样。也就是说,您的isValid方法需要返回self.matchingBrackets(s[1:],bracket)

此外,您定义matchingBrackets为一种方法,除了 之外仅采用一个参数self,但随后您将两个参数传递给它s[1:]bracket。这也是为什么不清楚变量bracket指的是什么的原因。

另外,我真的不明白function(s[1:],type)指的是什么。它是否在您发布的代码片段之外定义了它?

最后,我不确定该函数的逻辑是否符合 Leetcode 问题的要求。


推荐阅读