本文介绍了Python中函数参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尽管可以将默认值设置为python中的函数参数:
def my_function(param_one = 'default')
...
似乎无法访问当前(self):
class MyClass(..):
$ b def my_function(self,param_one = self.one_of_the_vars):
...
我的问题: p>
这是真的,我无法访问当前实例来设置函数中的默认参数吗?
If这不是可能的:原因是什么,它可能在未来的python版本中可能吗?
解决方案
它写成:
def my_function(self,param_one = None):#如果None为vaild,则为定制哨兵
如果param_one为None:
param_one = self.one_of_the_vars
我认为可以肯定的是,由于 self
直到函数启动时才真正存在......(你不能在它自己的定义中引用它,就像其他的一样)
例如:你不能做 d = {'x':3,'y':d ['x'] * 5}
While it is possible to set default values to function parameters in python:
def my_function(param_one='default')
...
It seems not to be possible to access the current instance (self):
class MyClass(..):
def my_function(self, param_one=self.one_of_the_vars):
...
My question(s):
- Is this true that I cannot access the current instance to set the default parameter in functions?If it is not possble: what are the reasons and is it imaginable that this will be possible in future versions of python?
解决方案
It's written as:
def my_function(self, param_one=None): # Or custom sentinel if None is vaild
if param_one is None:
param_one = self.one_of_the_vars
And I think it's safe to say that will never happen in Python due to the nature that self
doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)
For example: you can't do d = {'x': 3, 'y': d['x'] * 5}
这篇关于Python中函数参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!