使用当前类实例的属性作为方法参数的默认值 [英] Using an attribute of the current class instance as a default value for method's parameter

查看:69
本文介绍了使用当前类实例的属性作为方法参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
实例方法结果的参数默认值

虽然可以在python中为函数参数设置默认值:

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):
        ...

我的问题:

  • 是真的我无法访问当前实例来设置函数中的默认参数吗?
  • 如果不可能,原因是什么?是否可以想象在将来的python版本中实现?

推荐答案

它写为:

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

并且我可以肯定地说,由于 self 直到函数开始才真正存在的本质,所以在Python中永远不会发生...(您不能在函数中引用它),它自己的定义-像其他所有东西一样

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)

例如:您不能执行 d = {'x':3,'y':d ['x'] * 5}

这篇关于使用当前类实例的属性作为方法参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆