我有一个正常结构化的 Python 程序,其中包含导入语句、类定义、其他例程和一些调用类中的方法的“主”语句(按此顺序)。导入后的打印语句打印“ok”
Python 2.7.2
我在类方法中得到一个 nameError。
print >> common, ...
NameError: 'common' is not defined
common
之前在相同的方法中使用过,但之前的引用没有引起错误。
common
在许多方法中使用 - 物理移动此方法没有效果:错误仍然在此方法中的同一行。
错误发生在方法被调用之前,并且在任何“main”语句被执行之前。将 return 作为方法中的第一个可执行语句无效。这一切显然都发生在类定义时。
如果我注释掉这些print >> common
语句,我会在同一方法中得到不同的 NameError。
我不知道如何在“定义时间”在方法中获取 NameError。
有任何想法吗?方法如下:
下面的 x = z ** 2应该会生成 NameError: there is no z. 不执行所有函数定义之后的打印语句。
"""code below"""
@classmethod
def show_role_map(cls):
"""show jobs within roles, with total days, with percents of totals"""
return
raise ZeroDivisionError
return
print >> common, "xyzzy"
x = z ** 2
p = Performance("Traveler: show_role_map")
print "\tshow_role_map"
roles = cls.role_map.keys()
roles.sort()
header ("Qualitative Role Map")
role_totals = collections.defaultdict(float)
job_totals = collections.defaultdict(float)
for name in Traveler.roster:
trav = Traveler.roster[name]
for day in trav.roles:
frac = 1.0 / len(trav.roles[day])
for role in trav.roles[day]:
role_totals[role] += frac
for day in trav.jobs:
frac = 1.0 / len(trav.jobs[day])
for job in trav.jobs[day]:
job_totals[job] += frac
role_total = sum(role_totals.values())
job_total = sum(job_totals.values())
assert abs(role_total - job_total) <= 1e-6
print >> common, "Total Role days =", role_total
print >> common, "Total Job days =", job_total
print >> common
for role in roles:
if role_totals[role] == 0: continue
print >> common, "\t%12s %51.1f %12s %12.3f" %\
(role, role_totals[role], \
"", 100.0 * role_totals[role] / role_total)
jobs = list(cls.role_map[role])
jobs.sort (key = lambda x: (job_totals[x], x), reverse = True)
for index, job in enumerate(jobs, 1):
if job_totals[job] == 0: continue
print role, job, role_totals[role], job_totals[job]
print >> common, "\t\t%6d. %35s %12.1f % 12.3f %12.3f" % \
(index, job, job_totals[job], \
100.0 * job_totals[job] / role_totals[role],
100.0 * job_totals[job] / role_total)
print >> common
print >> common, "\n", "_" * 60, "\n" #--ERROR OCCURS FOR THIS LINE ****************
print >> common, "\nRoles in Total Tripday order\n"
roles = role_totals.keys()
roles.sort (order = lambda x: (role_totals[x], x), reverse = True)
for index, role, in enumerate(roles,1):
print >> common, "%6d. %15s %12.1f %12.3f" % \
(index, role, role_totals[role], \
100.0 * role_totals[role]/role_total)
print >> common, "\n", "_" * 60, "\n"
print >> common, "\nDetailed Trip Roles in Total Tripday order"
jobs = job_totals.keys()
jobs.sort (key = lambda x: (job_totals[x], x), reverse = True)
for index, job in jobs:
print >> common, "%6d. %35s %12.1f %12.3f" % \
(index, job, job_totals[job], 100.0 * job_totals[job] / job_total)
p.close()