using attributes as defaults

Peter Otten __peter__ at web.de
Fri Feb 4 22:17:48 CET 2011


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?

No. The defaults are evaluated once, when the method is created, and self.a 
is only known after the instance has been created. 

The Python idiom to achieve what you want is

def MyMethod(self, a=None):
    if a is not None:
        self.a = a

If None is a valid value for self.a you can use a custom sentinel instead:

missing = object()
class MyClass:
    def MyMethod(self, a=missing):
        if a is not missing:
            self.a = a




More information about the Python-list mailing list