default argument in method
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Dec 30 15:03:55 EST 2010
On Thu, 30 Dec 2010 11:26:50 -0800, DevPlayer wrote:
> There's some_object.some_method.func_defaults
Not quite -- method objects don't expose the function attributes
directly. You need some_object.some_method.im_func to get the function
object, which then has a func_defaults attribute.
> and
> some_function.func_defaults both are a settable attribute. How to set
> the methods func_defaults?
(1) You shouldn't mess with func_defaults unless you know what you're
doing.
(2) If you do know what you are doing, you probably won't want to mess
with func_defaults.
(3) But if you insist, then you would so the same way you would set any
other object's attribute.
>>> class C(object):
... def method(self, x=[]):
... print x
...
>>> C().method()
[]
>>> function = inst.method.im_func
>>> function.func_defaults
([],)
>>> function.func_defaults = ("spam",)
>>> inst.method()
spam
(4) Seriously, don't do this.
> You'd have to have code in
> _getattribute__(yourmethod) if not __getattr__(yourmethod)
>
> def __getattribute__(self, attr):
> if attr == self.my_method:
> # something like this, but i'm probably a little off
> # you might need to use super or something to prevent
> recursive __getattribute__ calls here
> self.my_method.func_defaults = self.foo
*cries*
A much better solution would be:
class MyClass:
def my_method(self, x=None):
if x is None:
x = self.foo
...
Don't write slow, confusing, complex, convoluted, self-modifying code
when you can write fast, simple, straight-forward, obvious code. Unless
you're doing it to win a bet.
--
Steven
More information about the Python-list
mailing list