簡體   English   中英

NameError:未定義全局名稱,為什么會收到該錯誤?

[英]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

您不僅需要調用len_link需要調用Solution.len_link 否則,Python希望它成為全局范圍內的名稱。

另外,由於len_link不采用self參數,因此需要使用@staticmethod進行修飾:

    @staticmethod
    def len_link(A):

或者在該類之外創建一個函數,這樣您就可以全局調用它或使用classname.functionname()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM