[Tutor] Default parameter in class method
Kent Johnson
kent37 at tds.net
Tue Oct 7 16:18:00 CEST 2008
On Tue, Oct 7, 2008 at 10:08 AM, Daniele <d.conca at gmail.com> wrote:
> Hi all,
> I know very little about OOP in Python, I'm working on it but, for the
> time being, here's my problem:
> I want to create a method of a class with a default value. The problem
> is that this default value should be an instance field of that same
> class. For example:
>
> class Test():
> def __init__(self):
> self.field='Default'
>
> def myMethod(self, parameter=self.field):
> pass
>
> I'm getting an error like "name 'self' is not defined"; it seems I
> cannot access self.field in the method definition. Is there a
> work-around (or maybe just the proper way to do it)?
def myMethod(self, parameter=None):
if parameter is None:
parameter = self.field
If None is actually a valid value for parameter, you can create a
unique marker object:
outside the class:
_marker = object()
then:
def myMethod(self, parameter=_marker):
if parameter==_marker:
parameter = self.field
Kent
More information about the Tutor
mailing list