简体   繁体   English

将函数传递给Python中的可选参数

[英]Pass function to optional argument in Python

I am trying to pass a function, which doesn't take any input and returns some value. 我试图传递一个函数,该函数不接受任何输入并返回一些值。 The function is defined inside the class. 该函数在类内部定义。 However, it is throwing following error: 但是,它引发以下错误:

NameError: name 'self' is not defined

Please see the sample code below: 请参见下面的示例代码:

class Test():
    def rand(self):
        return 4

    def print_rand(self, num=self.rand()):
        print num

t = Test()
print t.print_rand()

Any workaround, please? 有什么解决方法吗? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC. 请注意,我在Ubuntu 14.04 LTS PC上使用Python 2.7。

You can't do it that way. 你不能那样做。

And that's a good thing - because the default is evaluated at function creation (ie, not when it's called). 这是一件好事-因为默认值是在函数创建时评估的(即,不是在调用时)。 If it did happen to work, then the random number would have been generated when the program first loads this function, and then kept the same random number for every call afterwards. 如果确实起作用,那么在程序首先加载此函数时会生成随机数,然后在以后的每次调用中都保留相同的随机数。

This should give you the effect you want though; 这应该可以给您想要的效果;

def print_rand(self, num=None):
    if num is None:
        num = self.rand()
    # ...

It's not possible using self as your optional argument but defining static properties would work. 使用self作为您的可选参数是不可能的,但是定义静态属性是可行的。

https://repl.it/@marksman/ravijoshi https://repl.it/@marksman/ravijoshi

class Test(object):
    rand = 4 # statically defined

    def print_rand(self, num=rand):
        print(num)

t = Test()
t.print_rand()

If you have to define num as a method then what @Shadow said is the best way to go, unless num can also be passed a value of None . 如果必须将num定义为方法,那么@Shadow所说的是最好的方法,除非num也可以传递None值。

Another option is simply defining a function that doesn't take a self, and just calling it in your params as a normal function. 另一个选择是简单地定义一个不带自我的函数,然后将其作为常规函数在您的参数中调用。

class Test():
    def rand():
        return 4

    def print_rand(self, num=rand()):
        print num

t = Test()
print t.print_rand()

If you actually intend on not accessing anything within the instance, and will be returning some constant value, you could define it as a @staticmethod. 如果您实际上打算不访问实例中的任何内容,并且将返回某个常量值,则可以将其定义为@static方法。

That all being said, I am not sure what the use case is for calling a method to get a default value right within the function parameter declaration. 综上所述,我不确定在函数参数声明中调用方法以获取默认值的用例是什么。 It's better to explicit like @Shadow's post said for something that's uncommon. 最好像@Shadow的帖子所说的那样显式表示一些不常见的内容。 It'll save you and someone else some good time in the future. 它将为您和其他人节省将来的美好时光。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM