using attributes as defaults
Jean-Michel Pichavant
jeanmichel at sequans.com
Tue Feb 8 05:19:16 EST 2011
Westley MartÃnez wrote:
> On Fri, 2011-02-04 at 13:08 -0800, Wanderer wrote:
>> I want to give the option of changing attributes in a method or using
>> the current values of the attributes as the default.
>>
>> class MyClass():
>> """ my Class
>> """
>> def __init__(self):
>> """ initialize
>> """
>> self.a = 3
>> self.b = 4
>>
>> def MyMethod(self, a = self.a, b = self.b)
>> """ My Method
>> """
>> self.a = a
>> self.b = b
>> DoSomething(a, b)
>>
>> The above doesn't work. Is there a way to make it work?
>>
>> Thanks
>>
>>
> This doesn't work because you can't reference keyword arguments in the
> keyword argument array. This will work:
> class MyClass:
>
> def __init__(self):
> """ initialize
>
> Really? These are the worst docstrings ever.
>
> """
> self.a = 3
> self.b = 4
>
> def MyMethod(self, a=None, b=None)
> if a is not None:
> self.a = a
> if b is not None:
> self.b = b
> DoSomething(a, b)
There is an alternative to this None thing:
Don't use optional arguments. Optional arguments are fine ,but I found
myself avoiding using them is often a better choice.
Quoting the zen of python: "Explicit is better than implicit."
If the reason for using optional arguments is that it'll take you 2 sec
less to write the method call, then it sounds kind of wrong. Any other
reason would be valid I guess.
I personnaly use optional arguments only to keep backward compatibility
when changing a method signature.
JM
More information about the Python-list
mailing list