Python Class: Lambda 名称错误 - 名称未定义

Python Class: Lambda Name Error - Name not defined

我是 Python 3.6 的初学者。 我正在尝试创建一个名为 'Week' 的 class,它将执行某些操作并最终打印变量 'avg_mon'.

的值

为了计算'avg_mon'的值,我使用了匿名函数'lambda'。

from datetime import datetime
from datetime import date
from operator import add
from operator import itemgetter

class Week():
    blank_mon=[0]*24
    sum_mon=blank_mon
    count_mon=0

    print ("Blank Monday: ",blank_mon)
    #curr_mon=[1,0,2,0,3,0,4,0,5,0,3,0,3,0,2,0,1,0,2,0,1,0,1,0]
    curr_mon=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
    print ("Current Monday",curr_mon)
    count_mon = count_mon + 1
    print ("Monday Count:",count_mon)
    sum_mon=list(map(add,sum_mon,curr_mon))                   #Adds all the Mondays together for each hour
    print ("Total sum of all Mondays::",sum_mon)
    avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon))   #Gets the average of the Mondays for each hour
    print ("Average Monday::",avg_mon)


mon = Week()

当我执行代码时,出现以下错误。 我在我的代码中没有看到任何 spelling/naming 错误。 我无法弄清楚这种错误背后的原因。

Blank Monday:  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Current Monday [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
Monday Count: 1
Total sum of all Mondays:: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
Traceback (most recent call last):
File "C:\Users\Admin\Documents\GitHub\Doze\functest.py", line 27, in <module>
class Week():
File "C:\Users\Admin\Documents\GitHub\Doze\functest.py", line 40, in Week
avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon))   #Gets the average of the Mondays for each hour
File "C:\Users\Admin\Documents\GitHub\Doze\functest.py", line 40, in <lambda>
avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon))   #Gets the average of the Mondays for each hour
NameError: name 'count_mon' is not defined

您可能想将部分代码放入构造函数中。如所写,它全部定义为 class 的一部分,这导致了您的问题:调用 lambda 函数时 count_mon 不在范围内。

将此代码移动到 __init__ 函数中:

class Week(): 
    def __init__(self):
        blank_mon=[0]*24
        sum_mon=blank_mon
        count_mon=0

        print ("Blank Monday: ",blank_mon)
        #curr_mon=[1,0,2,0,3,0,4,0,5,0,3,0,3,0,2,0,1,0,2,0,1,0,1,0]
        curr_mon=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
        print ("Current Monday",curr_mon)
        count_mon = count_mon + 1
        print ("Monday Count:",count_mon)
        sum_mon=list(map(add,sum_mon,curr_mon))                   #Adds all the Mondays together for each hour
        print ("Total sum of all Mondays::",sum_mon)
        avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon))   #Gets the average of the Mondays for each hour
        print ("Average Monday::",avg_mon)

以下是为什么会发生这种情况的完整解释:Accessing class variables from a list comprehension in the class definition