如何正确的创建多个对象?

jarodzhao 2020-10-21 09:01:49
按照下面的代码,输出的全是9。
而想要的是每次循环都创建一个对象来容纳不同的数据,请教如何可以在每次循环中都创建一个新对象?


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)


...全文
193 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
jarodzhao 2020-10-23
  • 打赏
  • 举报
回复
多谢,受益良多!
jarodzhao 2020-10-22
  • 打赏
  • 举报
回复
引用 3 楼 天不绝我 的回复:

for idx in range(len(comments)):
        print(comments[idx].idx)
看这个写法,就是别的语言转来的
一直做JAVA和前端,最近在看 python 请问,python 常规的写法是什么?
crifan 2020-10-22
  • 打赏
  • 举报
回复
Python中 循环 有多种写法 其中简单的,比如:

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))
就容易看出区别了。
jarodzhao 2020-10-21
  • 打赏
  • 举报
回复
为什么不加括号,实例化的对象会被再次引用?!
引用 楼主 jarodzhao 的回复:
按照下面的代码,输出的全是9。 而想要的是每次循环都创建一个对象来容纳不同的数据,请教如何可以在每次循环中都创建一个新对象?


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)


欢乐的小猪 2020-10-21
  • 打赏
  • 举报
回复


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)


放风喽 2020-10-21
  • 打赏
  • 举报
回复

for idx in range(len(comments)):
print(comments[idx].idx)

看这个写法,就是别的语言转来的
手无护鸡之力 2020-10-21
  • 打赏
  • 举报
回复
第 9 行 :

comment = Comment()   # 实例化需要加括号
你没加括号,赋值操作,comment 等同于类 Comment ,等同于给类 Comment 添加静态属性 idx

Comment.idx = i    
所以你 append 的是类对象 Comment,并不是它的实例, idx 是 Comment 的静态属性,最终赋值9

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧