【问题标题】:Setting argument defaults from arguments in python从python中的参数设置参数默认值
【发布时间】:2015-02-19 06:34:57
【问题描述】:

我正在尝试为我定义的函数中的参数设置默认值。我还希望另一个参数具有依赖于另一个参数的默认值。在我的示例中,我正在尝试绘制氢的量子力学波函数,但您无需了解物理学即可帮助我。

def plot_psi(n,l,start=(0.001*bohr),stop=(20*bohr),step=(0.005*bohr)):

n 是主量子数,l 是角动量,start,stop,step 是我计算的数组。但我需要的是stop的默认值实际上取决于n,因为n会影响波函数的大小。

def plot_psi(n,l,start=(0.001*bohr),stop=((30*n-10)*bohr),step=(0.005*bohr)):

将是我想要的,但 n 尚未定义,因为该行不完整。有什么解决办法吗?或者有另一种安排方式的想法?谢谢

【问题讨论】:

    标签: python python-2.7 arguments default


    【解决方案1】:

    使用None作为默认值,计算函数内部的值,像这样

    def plot_psi(n, l, start=(0.001*bohr),stop=None,step=(0.005*bohr)):
        if stop is None:
            stop = ((30*n-10)*bohr)
    

    【讨论】:

    • 不应该是if stop is None吗?
    猜你喜欢
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2015-11-05
    • 2018-01-22
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    相关资源
    最近更新 更多