[Tutor] Help on class

Steven D'Aprano steve at pearwood.info
Sat Sep 28 06:44:25 CEST 2013


On Fri, Sep 27, 2013 at 10:07:39PM +0800, bharath ks wrote:
> Hello,
> 
> May i know why object 'c' does not prompt for employee name and 
> employee id in the following code i get out put as 

Default values in Python functions and methods are evaluated once only, 
when the function or method is defined ("compile time"), not each time 
it is run.

You can test this yourself:

import time
def long_function():
    # Simulate a long-running calculation
    print("Calculation started at %s" % time.ctime())
    time.sleep(30)
    print("Calculation completed at %s" % time.ctime())
    return 42


def test(value=long_function()):
    print(value)


If you run this code, as I did, you will get something like:

py> def test(value=long_function()):
...     print(value)
...
Calculation started at Sat Sep 28 14:37:38 2013
Calculation completed at Sat Sep 28 14:38:08 2013

only once, when the test function is created. Then, you can run that 
function as often as you like without the lengthy calculation being 
repeated:


py> test()
42
py> test()
42
py> test(23)
23
py> test()
42


This is called "eager evaluation of default arguments", as opposed to 
"lazy evaluation of default arguments". To get lazy evaluation, stick 
the code inside the function, with a sentinel value:

py> def test2(value=None):
...     if value is None:
...         value = long_function()
...     print(value)
...
py> test2()
Calculation started at Sat Sep 28 14:41:08 2013
Calculation completed at Sat Sep 28 14:41:38 2013
42
py> test2(23)
23
py> test2()
Calculation started at Sat Sep 28 14:42:13 2013
Calculation completed at Sat Sep 28 14:42:43 2013
42


-- 
Steven


More information about the Tutor mailing list