如何将实例成员的默认参数值传递给方法?
作者:互联网
我想使用实例的属性值将默认参数传递给实例方法:
class C:
def __init__(self, format):
self.format = format
def process(self, formatting=self.format):
print(formatting)
尝试时,我收到以下错误消息:
NameError: name 'self' is not defined
我希望该方法的行为如下:
C("abc").process() # prints "abc"
C("abc").process("xyz") # prints "xyz"
这里有什么问题,为什么这不起作用?我怎么能做这个工作?
解决方法:
您无法将此定义为默认值,因为在定义任何实例之前定义方法时会计算默认值.通常的模式是做这样的事情:
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仅在格式为None时使用.
要演示默认值的工作方式,请参阅此示例:
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只被调用一次,并且在调用函数之前发生了!
标签:default-arguments,python,instance-variables 来源: https://codeday.me/bug/20190915/1805806.html