Passing data attributes as method parameters

Ben Cartwright bencvt at gmail.com
Sun Apr 23 19:41:26 EDT 2006


Panos Laganakos wrote:
> I'd like to know how its possible to pass a data attribute as a method
> parameter.
>
> Something in the form of:
>
> class MyClass:
>     def __init__(self):
>         self.a = 10
>         self.b = '20'
>
>     def my_method(self, param1=self.a, param2=self.b):
>         pass
>
> Seems to produce a NameError of 'self' not being defined.

Default arguments are statically bound, so you'll need to do something
like this:

class MyClass:
    def __init__(self):
        self.a = 10
        self.b = '20'

    def my_method(self, param1=None, param2=None):
        if param1 is None:
            param1 = self.a
        if param2 is None:
            param2 = self.b

--Ben




More information about the Python-list mailing list