Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在类内设置默认参数?_Python_Class_Oop_Default Parameters - Fatal编程技术网

Python 如何在类内设置默认参数?

Python 如何在类内设置默认参数?,python,class,oop,default-parameters,Python,Class,Oop,Default Parameters,我正在创建一个二叉搜索树,我想使用递归实现有序遍历,我需要为其传入根值,在本例中是self.root class BST: def __init__(self): self.root = None def inOrder(self, root): if root == None: return self.inOrder(root.left) print(root.data, end=&quo

我正在创建一个二叉搜索树,我想使用递归实现有序遍历,我需要为其传入根值,在本例中是
self.root

class BST:
    def __init__(self):
        self.root = None

    def inOrder(self, root):
        if root == None:
            return
        self.inOrder(root.left)
        print(root.data, end=" ")
        self.inOrder(root.right)
如何将
root
的默认值传递为等于
self.root
? 如果我使用:

class BST:
    def __init__(self):
        self.root = None

    def inOrder(self, root = self.root):
        if root == None:
            return
        self.inOrder(root.left)
        print(root.data, end=" ")
        self.inOrder(root.right)

它显示了一个错误,即未定义
self

即使这是可能的,也不是一个好主意。用作默认参数的对象是在首次解释代码时设置的,而不是每次调用该方法时设置的。这意味着当第一次解释代码时,
self.root
必须存在,并且每次使用默认参数时,它都会引用原始的
self.root
对象;调用该方法时,self.root并非碰巧是什么。正是因为这个原因,您真的不应该将可变对象作为默认参数。对一个函数的多个调用都使用相同的可变默认参数,这会导致错误

典型的解决方法是默认设置为
None
,然后检查:

def inOrder(self, root=None):
    if root is None:
        root = self.root
    . . .
不幸的是,这在这里不起作用,因为
None
在函数中有特殊意义。您可以改为使用sentinel对象:

sentinel = object()  # A unique object

. . .

def inOrder(self, root=sentinel):
    if root is sentinel: 
        root = self.root
    . . .
或者,您可以更改程序,使
None
不是该方法的有效参数,然后使用
None
而不是
sentinel