Default parameter for a method
Terry Reedy
tjreedy at udel.edu
Wed Apr 16 23:06:25 EDT 2008
"John Nagle" <nagle at animats.com> wrote in message
news:48065d11$0$36390$742ec2ed at news.sonic.net...
| s0suk3 at gmail.com wrote:
| > I wanted to know if there's any way to create a method that takes a
| > default parameter, and that parameter's default value is the return
| > value of another method of the same class. For example:
| >
| ...
|
| >
| > def meth2(self, arg=meth1()):
|
| Not good. If the default value of an argument is mutable, there
| are wierd effects, because the default value is bound once when the
| class is created, then shared between all later uses. This is almost
| never what was wanted or intended, and it's a common source of subtle
| bugs.
|
| In general, default values should be immutable constants only.
Then one would have to restrict default args to immutable builtins.
There is no way to determine (without reading code) whether instances of a
user-defined class are mutable or not.
tjr
More information about the Python-list
mailing list