Skip to main content
 首页 » 编程设计

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

2025年05月04日9Terrylee

这是我的类栏:

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) 

1) 我正在尝试初始化最高价、最低价和最低价,无论开盘是什么。这是执行此操作的正确方法吗?

2) 当我执行 print(str(bar)) 时,我得到有趣的输出,例如...

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

请您参考如下方法:

如果您将函数编写为

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) 

你会得到一个 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) 

此外,您可能希望使用“open_”而不是“open”作为参数名称,只是为了避免混淆(并暂时隐藏)内置函数。