Passing data attributes as method parameters

Jay Parlar jparlar at cogeco.ca
Sun Apr 23 23:45:57 EDT 2006


On Apr 23, 2006, at 4:59 PM, Panos Laganakos wrote:

> Thanks Ben.
>
> What does it mean that they're statically bound?
>
> It seems weird that I'm not able to access variables in the class
> namespace even though these attributes come into existance after class
> instantiation.
>

The parameters are "put together" and bound to the method when the 
class is defined, *not* after class instantiation.

As an example:

 >>> class MyClass:
...  def my_method(self, param1 = []):
...   print param1
...   param1.append(5)
...
 >>> x = MyClass()
 >>> x.my_method()
[]
 >>> x.my_method()
[5]
 >>> y = MyClass()
 >>> y.my_method()
[5, 5]
 >>> y.my_method()
[5, 5, 5]
 >>>


Usually, people use immutable datatypes as default parameter values, so 
it doesn't cause a problem.

And an even more illustrative example:

 >>> class M:
...  x = 2
...  def my_method(self, param = M.x):
...   pass
...
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 3, in M
NameError: name 'M' is not defined


The class is still being built when the method is created, so even the 
name "M" doesn't exist yet.




Ben's solution is probably the best way to do what you're looking for.

Jay P.




More information about the Python-list mailing list