如何使用非默认参数的值作为Python中默认参数的默认值?

Jos*_*hua 1 python default-value default-arguments

这是我的班级栏:

class Bar:
    def __init__(self, start, end, open, volume, high=open, low=open, last=open):
        self.start = start
        self.end = end
        self.open = open
        self.high = high
        self.low = low
        self.last = last
        self.volume = int(volume)

    def __str__(self):
        return self.start.strftime("%m/%d/%Y\t%H:%M:%S") + "\t" + self.end.strftime("%H:%M:%S") + "\t" +str(self.open) + "\t" + str(self.high) + "\t" + str(self.low) + "\t" + str(self.last) + "\t" + str(self.volume)
Run Code Online (Sandbox Code Playgroud)

1)我试图初始化高,低和最后的任何打开.这是正确的方法吗?

2)当我打印(str(bar))我得到有趣的输出,如...

03/13/2012 12:30:00 13:30:00 138.91 <built-in function open> 138.7 <built-in function open> 13177656

che*_*ner 5

如果你把你的功能写成了

def __init__(self, start, end, foo, volume, high=foo, low=foo, last=foo):
    self.start = start
    self.end = end
    self.open = foo
    self.high = high
    self.low = low
    self.last = last
    self.volume = int(volume)
Run Code Online (Sandbox Code Playgroud)

你会得到一个NameError抱怨名称foo没有定义.这是因为参数的默认值不能引用另一个参数,当您尝试获取其值时,该参数尚未定义.(默认值在定义方法时设置,而不是在调用方法时设置.)

但是,open Python中的内置函数,因此它定义; 它只是不是open你的意思.这样做的正确方法可能是

class Bar:
    def __init__(self, start, end, open, volume, high=None, low=None, last=None):
        self.start = start
        self.end = end
        self.open = open
        self.high = open if high is None else high
        self.low = open if low is None else low
        self.last = open if last is None else last
        self.volume = int(volume)
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望使用"open_"而不是"open"作为参数名称,以避免混淆(并暂时遮蔽)内置函数.