python instance variables as optional arguments

为君一笑 提交于 2021-02-18 11:23:09

问题


In python, is there a way I can use instance variables as optional arguments in a class method? ie:

def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
    # do stuff....

Any help would be appreciated.


回答1:


Try this:

def foo(self, blah=None):
    if blah is None: # faster than blah == None - thanks to kcwu
        blah = self.instance_var



回答2:


All the responses suggesting None are correct; if you want to make sure a caller can pass None as a regular argument, use a special sentinel and test with is:

class Foo(object):
  __default = object()
  def foo(self, blah=Foo.__default):
    if blah is Foo.__default: blah = self.instavar

Each call to object() makes a unique object, such that is will never succeed between it and any other value. The two underscores in __default mean "strongly private", meaning that callers know they shouldn't try to mess with it (and would need quite some work to do so, explicitly imitating the name mangling that the compiler is doing).

The reason you can't just use the code you posted, btw, is that default values evaluate when the def statement evaluates, not later at call time; and at the time def evaluates, there is as yet no self from which to take the instance variable.




回答3:


no, because the instance doesn't exist when class function definition time

You have to rewrite as following

def function(self, arg1=val1, arg2=val2, arg3=None):
    if arg3 is None:
        arg3 = self.instance_var

This is slightly different to original one: you cannot pass arg3 with None value if you really want.

Alternative solution:

def function(self, arg1=val1, arg2=val2, **argd):
    arg3 = argd.get('arg3', self.instance_var)



回答4:


def foo(self, blah=None):
    blah = blah if not blah is None else self.instance_var

This works with python 2.5 and forwards and handles the cases where blah is empty strings, lists and so on.




回答5:


An alternative way of doing this would be:

def foo(self, blah=None):
    blah = blah or self.instance_var

This shorter version looks better, specially when there is more than one optional argument.

Use with care. See the comments below...



来源:https://stackoverflow.com/questions/867115/python-instance-variables-as-optional-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!