NameError:变量未定义

时间:2019-06-11 02:57:16

标签: python nameerror

很抱歉给您带来混乱。使用全局引用在方法内部提到了变量“ head”。但这不是!

这是我的代码:

case  .success(let code):

1 个答案:

答案 0 :(得分:0)

使用__init__魔术方法,并声明这些 class 实例变量,其中self(实例)是它要分配给的对象(self是实际上是班级):

class Solution:
    def __init__(self):
        self.head = None
        self.current = None
    def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
        m = nums.index(max(nums))
        if not self.head:
            self.head = TreeNode()
            self.head.val = max(nums)
            self.head.left = constructMaximumBinaryTree(self, nums[:m])
            self.head.right = constructMaximumBinaryTree(self, nums[m + 1:])
        elif not current:
            current = self.head
        else:
            pass
        current.left = constructMaximumBinaryTree(self, nums[:m])
        current.right = constructMaximumBinaryTree(self, nums[m+1:])
        return self.head