NameError: global name is not defined, why am I getting that error?

NameError: global name is not defined, why am I getting that error?

我正在尝试实现一些功能,但我在使用 len_link 功能时遇到错误: NameError: global name 'len_link' is not defined 虽然其他功能运行良好,但有任何线索说明为什么会首先发生此错误吗?

class Solution:
        # @param A : head node of linked list
        # @param B : head node of linked list
        def len_link(A):
            temp=A.head
            count=0
            while(temp):
                count+=1
                temp=temp.next
            return count

        def longerlist(B,n):
            for i in range(n):
                B = B.next
            return B

        def getIntersectionNode(self, A, B):
            m = len_link(A)
            n = len_link(B)
            d = abs(m-n)
            if m>n :
                A = longerlist(A,n)
            elif m<n:
                B = longerlist(B,n)
            while A!= None and B!= None:
                if A.val == B.val:
                    return A
                A = A.next
                B = B.next

您需要致电 Solution.len_link,而不仅仅是 len_link。否则 Python 期望它是全局范围内的名称。

此外,由于len_link不带self参数,需要用@staticmethod修饰:

    @staticmethod
    def len_link(A):

或在 class 之外创建一个函数,这样您就可以全局调用它或使用 classname.functionname()