37,720
社区成员
发帖
与我相关
我的任务
分享
class Comment():
def __init__(self):
pass
def lop():
comments = []
for i in range(10):
comment = Comment
comment.idx = i
comments.append(comment)
return comments
if __name__ == '__main__':
comments = lop()
# print(len(comments))
for idx in range(len(comments)):
print(comments[idx].idx)
for each_single_comment in comments:
print(each_single_comment.idx)
另外,如果搞不清
Comment
和
Comment()
可以借助于type去看看打印出的类型
comment = Comment
print("type(comment)=%s" % type(comment))
和:
comment = Comment()
print("type(comment)=%s" % type(comment))
就容易看出区别了。
class Comment():
def __init__(self):
pass
def lop():
comments = []
for i in range(10):
comment = Comment()
comment.idx = i
comments.append(comment)
return comments
if __name__ == '__main__':
comments = lop()
# print(len(comments))
for idx in range(len(comments)):
print(comments[idx].idx)
for idx in range(len(comments)):
print(comments[idx].idx)
comment = Comment() # 实例化需要加括号
你没加括号,赋值操作,comment 等同于类 Comment ,等同于给类 Comment 添加静态属性 idx
Comment.idx = i
所以你 append 的是类对象 Comment,并不是它的实例, idx 是 Comment 的静态属性,最终赋值9