有时,使用默认参数(即空列表)似乎很自然.然而,Python在这些情况下会出现意外行为.
例如,我有一个功能:
def my_func(working_list = []):
working_list.append("a")
print(working_list)
Run Code Online (Sandbox Code Playgroud)
第一次使用默认值调用它将起作用,但之后的调用将使用不断更新的列表.
那么,获得我想要的行为的pythonic方法是什么(每个调用都有一个新的列表)?
我想使用实例的属性值将默认参数传递给实例方法:
class C:
def __init__(self, format):
self.format = format
def process(self, formatting=self.format):
print(formatting)
Run Code Online (Sandbox Code Playgroud)
尝试时,我收到以下错误消息:
NameError: name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)
我希望该方法的行为如下:
C("abc").process() # prints "abc"
C("abc").process("xyz") # prints "xyz"
Run Code Online (Sandbox Code Playgroud)
这里有什么问题,为什么这不起作用?我怎么能做这个工作?
嘿大家好,我正在努力简化我的一个作业问题并使代码更好一些.我正在使用的是二叉搜索树.现在我在我的Tree()类中有一个函数,它找到所有元素并将它们放入列表中.
tree = Tree()
#insert a bunch of items into tree
Run Code Online (Sandbox Code Playgroud)
然后我使用我的makeList()函数从树中获取所有节点并将它们放在一个列表中.makeList()我打电话给这个功能tree.makeList(tree.root).对我来说,这似乎有点重复.我已经调用了树对象,tree.所以这tree.root只是浪费一点点打字.
现在makeList函数是:
def makeList(self, aNode):
if aNode is None:
return []
return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)
Run Code Online (Sandbox Code Playgroud)
我想让aNode输入一个默认参数,例如aNode = self.root(这不起作用),这样我可以运行这个函数,tree.makeList().
第一个问题是,为什么不起作用?
第二个问题是,有没有办法可以运作?正如你所看到的那样,makeList()函数是递归的,所以我无法在函数的开头定义任何东西,或者我得到一个无限循环.
编辑 以下是所有要求的代码:
class Node(object):
def __init__(self, data):
self.data = data
self.lChild = None
self.rChild = None
class Tree(object):
def __init__(self):
self.root = None
def __str__(self):
current = self.root
def isEmpty(self):
if …Run Code Online (Sandbox Code Playgroud) num1 = self.var1在 function 中赋值时fiz,Python 说未解析的引用。这是为什么?
class Foo:
def __init__(self):
self.var1 = "xyz"
def fiz(self, num1=self.var1):
return
Run Code Online (Sandbox Code Playgroud) 我试图将一些Java代码转换为python等价物,以便我可以在两者之间进行接口.所以在Java中我有一些像这样的代码:
public int[] toArray(boolean order) {
return toArray(order, this.length());
}
public int[] toArray(boolean order, int length) {
...
}
Run Code Online (Sandbox Code Playgroud)
并且python中的逻辑等效项可能如下所示:
def to_array(self, order):
return self.to_array(order, self.length())
def to_array(self, order, length):
...
Run Code Online (Sandbox Code Playgroud)
除了... python不允许函数重载,相反它允许默认参数,所以,再次,你想要做这样的事情似乎合乎逻辑:
def to_array(self, order, length = self.length()):
...
Run Code Online (Sandbox Code Playgroud)
但是...这在python中也是不允许的,可能因为self直到函数体内才真正"存在".
那么在python中执行此操作的正确方法是什么?或者它是不可能的?
编辑:我意识到我在我的java代码中使用了void函数,它应该返回一个值,所以现在它们返回 int[]