Yugal Jindle Yugal Jindle - 1 year ago 178
Python Question

Python : How to pass default argument to instance method with an instance variable?

My Code :

class c:
def __init__(self, format):
self.format = format

def process(self, formatting=self.format)
print formatting

name 'self' is not defined

I want : (Desired output)

c("abc").process() # prints "abc"
c("abc").process("xyz") # prints "xyz"

  • Point out the problem ?

  • Workaround to get desired output ?

Answer Source

You can't really define this as the default value, since the default value is set before any instances exist. An easy work-around is to do something like this:

class C:
    def __init__(self, format):
        self.format = format

    def process(formatting=None):
        formatting = formatting if formatting is not None else self.format
        print formatting

self.format will only be used if formatting is equal to None.

To demonstrate the point of how default values work, see this example:

def mk_default():
    print "mk_default has been called!"

def myfun(foo=mk_default()):
    print "myfun has been called."

print "about to test functions"
myfun("testing again")

And the output here:

mk_default has been called!
about to test functions
myfun has been called.
myfun has been called.

Notice how mk_default was called only once (and before the function was ever called!)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download