using attributes as defaults

Stephen Hansen me+list/python at ixokai.io
Fri Feb 4 16:16:43 EST 2011


On 2/4/11 1:08 PM, 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?

The normal way to go about it would be to set the a/b arguments to None,
like so:

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

    DoSomething(self.a, self.b)

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20110204/7d29d43f/attachment.sig>


More information about the Python-list mailing list