Discuss / Python / 为什么类属性无法被创建?

为什么类属性无法被创建?

Topic source

白霓裳酱

#1 Created at ... [Delete] [Delete and Lock User]

首先说明一下: init是正确的,只是在这里显示有问题而已. 以下代码创建类的话,会失败,提示 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)

但如果删除name_list列表类属性的话(也就是以下代码),类和实例对象都是可以正常创建的

class Stu_B(object): name='student{}' other_name=name.format('A') def init(self): pass

b=Stu_B() print(b.name_list)

但问题是:同样都是format函数调用name属性,为什么存在列表表达式的时候就会出错呢? 求大神解答!!

白霓裳酱

#2 Created at ... [Delete] [Delete and Lock User]

最后一行代码手误:应该是: print(b.other_name)

白霓裳酱

#3 Created at ... [Delete] [Delete and Lock User]

class Stu_B(object): name='student{}' other_name=name.format('A') name_list = [] for i in 'BCDE': name_list.append(name.format(i)) def init(self): pass

b=Stu_B() print(b.name_list)

如果不用列表表达式,而用for循环进行列表元素添加的话,又是正常的,真心搞不懂,请大神解答!!


  • 1

Reply