[英]Python method defaults based off of class __init__ args
I want my methods defaults within a class to be set to what was passed in through the __init__
method. 我希望将类中的方法默认值设置为通过
__init__
方法传递的值。 Something like this: 像这样:
class Foo(object):
def __init__(self, loc=None):
self.loc = loc
def test(self, loc=self.loc):
print loc
test = Foo()
test.test()
>>> None
test = Foo('foobar')
test.test()
>>> foobar
Is this possible or another way of achieving this? 这有可能还是实现这一目标的另一种方式?
EDIT: I know this current code is not possible but something that would function like this is what I'm looking for. 编辑:我知道当前的代码是不可能的,但像这样的功能是我正在寻找的东西。
Thanks 谢谢
Default argument values are evaluated at the point of function definition in the defining scope, but self
is an argument only available during function call. 默认参数值在定义范围内的函数定义点进行评估,但是
self
是仅在函数调用期间可用的参数。
See an example: 看一个例子:
i = 5
def f(arg = i): print arg
i = 6
f()
will print 5. Visualization on python-tutor. 将打印5。在python-tutor上可视化 。
It is a common pattern to default an argument to None
and add a test for that in the code: 将参数默认设置为
None
并在代码中为此添加测试是一种常见的模式:
def test(self, loc = None):
if loc is None:
loc = self.loc
print loc
Do something like this: 做这样的事情:
def test(self, loc = None):
if loc is None:
loc = self.loc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.