如何将实例成员的默认参数值传递给方法? [英] How to pass a default argument value of an instance member to a method?
问题描述
我想使用实例的属性值将默认参数传递给实例方法:
I want to pass a default argument to an instance method using the value of an attribute of the instance:
class C:
def __init__(self, format):
self.format = format
def process(self, formatting=self.format):
print(formatting)
尝试此操作时,出现以下错误消息:
When trying that, I get the following error message:
NameError: name 'self' is not defined
我希望该方法的行为如下:
I want the method to behave like this:
C("abc").process() # prints "abc"
C("abc").process("xyz") # prints "xyz"
这是什么问题,为什么这不起作用?我怎么做呢?
What is the problem here, why does this not work? And how could I make this work?
推荐答案
您不能真正将其定义为默认值,因为默认值为在定义方法时(在任何实例存在之前)进行评估。通常的模式是执行以下操作:
You can't really define this as the default value, since the default value is evaluated when the method is defined which is before any instances exist. The usual pattern is to do something like this instead:
class C:
def __init__(self, format):
self.format = format
def process(self, formatting=None):
if formatting is None:
formatting = self.format
print(formatting)
self.format
仅如果格式
为无
,则使用此格式。
self.format
will only be used if formatting
is None
.
为演示默认值的工作原理,请参见以下示例:
To demonstrate the point of how default values work, see this example:
def mk_default():
print("mk_default has been called!")
def myfun(foo=mk_default()):
print("myfun has been called.")
print("about to test functions")
myfun("testing")
myfun("testing again")
输出如下:
mk_default has been called!
about to test functions
myfun has been called.
myfun has been called.
请注意 mk_default
仅被调用一次,那是在函数被调用之前发生的!
Notice how mk_default
was called only once, and that happened before the function was ever called!
这篇关于如何将实例成员的默认参数值传递给方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!