在创建类时,遇到很奇怪的问题,主要原因是提示引用了不存在的变量,以下用具体代码进行说明.class Stu_A(object):
name='student{}'
other_name=name.format('A') def __init__(self):
passa=Stu_A()
print(a.other_name)以上代码是可以正确运行的,但是如果再增加一个类属性的话(该类属性是以之前属性格式化而生成的列表),就会提示变量没有被定义的的错误,代码如下:class Stu_B(object):
name='student{}'
other_name=name.format('A')
name_list = [name.format(i) for i in 'BCDE'] def __init__(self):
pass
b=Stu_B()
print(b.name_list)Stu_B 这个类无法被创建提示的错误信息: NameError: name 'name' is not defined在Stu_A类中,other_name属性同样是用name属性格式化而来的,可以正常运行.但在Stu_B中,使用一个列表生成式去格式化name属性而创建一个列表,却不行呢?希望有大神能给解答一下,感谢!
1 回答

皈依舞
TA贡献1851条经验 获得超3个赞
在python3中:
[name.format(i) for i in 'BCDE']
等价于:
list(name.format(i) for i in 'BCDE')
这是一个函数调用。所以你如果要引用类属性name作为函数的变量,应该这样:
[类名.name.format(i) for i in 'BCDE']
- 1 回答
- 0 关注
- 508 浏览
添加回答
举报
0/150
提交
取消