2015-05-18 8 views
6

मैंने हमेशा सोचा था कि पायथन 2.7 फ़ंक्शंस उस क्षेत्र को संदर्भित करता है जिसे उन्होंने परिभाषित किया था। निम्नलिखित कोड पर विचार करें। दूसरा आउटपुट क्यों नहीं है "गणना: पाप"?पायथन क्लोजर को समझना

क्या कोड को संशोधित करने का कोई तरीका है, इसलिए यह अपेक्षित काम कर रहा है?

import math 

mymath = dict() 

for fun in ["sin", "cos"]: 
    def _impl(val): 
     print "calculating: %s" % fun 
     return getattr(math, fun)(val) 
    mymath[fun] = _impl 

# calculating: cos 
print mymath["cos"](math.pi) 

# calculating: cos <- why? 
print mymath["sin"](math.pi) 

उत्तर

7

जब समारोह कहा जाता है fun का मूल्य मूल्यांकन किया जाता है।

उदाहरण के लिए, fun एक वैश्विक चर है, और for लूप रन के बाद यह मान "cos" है।

मुझे लगता है कि आप फ़ंक्शन बनाते समय प्रतिस्थापित होने के लिए fun के मान की अपेक्षा करते हैं, लेकिन ऐसा नहीं है। फ़ंक्शन वैरिएबल के मान का मूल्यांकन करता है जब यह चलता है जैसा कि यह माना जाता है।

यह उस नामस्थान के बारे में नहीं है जिसमें आप फ़ंक्शन को परिभाषित करते हैं, लेकिन नामस्थान जिसमें आप फ़ंक्शन चलाते हैं।

import math 

mymath = dict() 

for fun in ["sin", "cos"]: 
    def _impl(val): 
     print "calculating: %s" % fun 
     return getattr(math, fun)(val) 
    mymath[fun] = _impl 


fun = 'tan' 
# will print and calculate tan 
print mymath["cos"](math.pi) 
2

इस कोड (जो आपकी इच्छानुसार काम करता है) से

my = {} 

def makefun(fun): 
    def _impl(x): 
    print fun, x 
    return _impl 

for fun in ["cos", "sin"]: 
    my[fun] = makefun(fun) 

# will print 'cos' 
my['cos'](1) 
fun = 'tan' 
# will print 'cos' 
my['cos'](2) 

ऐसा लगता है कि यह समारोह परिभाषा के नाम स्थान जो बंद की प्रकृति लेकिन बजाय नाम स्थान के बारे में निर्णय करता है प्रयुक्त चर और अधिक परीक्षण:

my = dict() 

fun = '' 

def makefun(): 
    global fun #This line is switched on or off 
    fun = 'sin' 
    def _impl(x): 
    print fun, x 
    return _impl 

test = makefun() 

#gives sin 1 
test(1) 
fun = 'cos' 
#gives sin 2 if line global fun is used 
#gives cos 2 if line global fun is NOT used 
test(2) 

तो सही व्याख्या है कि बंद के अपने तर्कों के लिए एक संदर्भ और नहीं एक मूल्य की बचत होती है हो रहा है।

0

मुझे लगता है कि आप चीजों को कठिन बनाने के लिए कोशिश कर रहे हैं:

creating sin function 
calculating: sin 
1.22464679915e-16 
creating cos function 
calculating: cos 
-1.0 
:

import math 

mymath = dict() 


def funcmaker(fun): 
    print "creating %s function" % fun 
    def calculate(val): 
     print "calculating: %s" % fun 
     return getattr(math, fun)(val) 
    return calculate 

print funcmaker("sin")(math.pi) 
print funcmaker("cos")(math.pi) 

कोड से ऊपर आप निम्नलिखित परिणाम देता है: का तरीका यहां बताया बंद के साथ यह कर सकते हैं है

संबंधित मुद्दे