整理一下木兰重现过程中 碰到并中文化 的报错和对应python代码(木兰的报错信息为运行对应木兰代码时的反馈信息),第一批十一个例程八种报错。在 Python 3.13.1 和 3.8 下测试。

例程对应报错

下标越界

print([1][2])

IndexError: list index out of range

木兰:取列表内容时,索引超出范围

try随意

try a=3:
  print(a)

3.8:AttributeError: enter 3.13:TypeError: ‘int’ object does not support the context manager protocol

木兰:

需要添加此属性:__enter__
参考:https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit

引用全局

x = 2

def a():
  x = x
a()

3.8:UnboundLocalError: local variable ‘x’ referenced before assignment

3.13:UnboundLocalError: cannot access local variable ‘x’ where it is not associated with a value

木兰:请先对本地变量‘x’赋值再引用

未定义‘名称’

这个 ‘name’ 的范围挺广。

例1:

print(b)

NameError: name ‘b’ is not defined

木兰:请先定义‘b’再使用

例2:

class P:

  def __init__(self):
    self.var = 1

  @staticmethod
  def test():
    print(self.var)
print(P().var)
P.test()

NameError: name ‘self’ is not defined

木兰:函数没有属性‘var’,看看‘self’

例3:

def add(number):
  return number + 1

def output(number):
  print(number)
output(number(2))

NameError: name ‘number’ is not defined

木兰:请先定义‘number’再使用

除零

print(1/0)

ZeroDivisionError: division by zero

木兰:请勿除以零

字典无键

d = {1: 'a', 3: 'c'}
print(d[4])

KeyError: 4

木兰:字典中不存在此键:4

字符串拼接

print("1" + 2)

TypeError: can only concatenate str (not “int”) to str

木兰:字符串只能拼接字符串,请将“int”先用 str() 转换

无属性

例1:

a = None
print(a.name)

AttributeError: ‘NoneType’ object has no attribute ‘name’

木兰:空变量没有属性‘name’,看看‘a’

例2:

import TypeDef
print(TypeDef.a)

AttributeError: module ‘TypeDef’ has no attribute ‘a’

木兰:同上

附:流程

转换木兰例程如 % 木兰 -p 测试/错误处理/try随意.ul 生成 python 代码,运行后获取python的报错输出。之后可以自动化。