Python中文
首页
教程
问答
标签
搜索
登录
注册
为什么这个Python类要复制另一个类的内容?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我试图理解Python中的一种疏远行为。在</p> <p>我有下一个python代码:</p> <pre><code>class IntContainer: listOfInts = [] def __init__(self, initListOfInts): for i in initListOfInts: self.listOfInts.append(i) def printInts(self): print self.listOfInts if __name__ == "__main__": intsGroup1 = [1,2,3,4] intsGroup2 = [4,5,6,7] intsGroups = [intsGroup1,intsGroup2] intsContainers = [] for ig in intsGroups: newIntContainer = IntContainer(ig) intsContainers.append(newIntContainer) for ic in intsContainers: print ic.listOfInts </code></pre> <p>我希望得到的东西是:</p> ^{pr2}$ <p>但我得到:</p> ^{3}$ <p>我检查了下一个问题:</p> <p><a href="https://stackoverflow.com/questions/1876905/why-is-python-reusing-a-class-instance-inside-in-function">why is python reusing a class instance inside in function</a></p> <p>还有很多Python的参考,但是我不明白发生了什么。我认为这与<code>newIntContainer</code>标识符的重用有关,但我对其理解不深。在</p> <p>为什么Python似乎重用了新对象的最后一个引用,即使我已将其添加到永久列表中?我能做些什么来解决这种行为?在</p> <p>谢谢;)</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>listOfInts已定义为类变量。在</p> <p>类变量由类的所有实例共享。在</p> <p>如果您想保存类相关的状态(一个典型的例子是当您想知道所创建的类的实例数时),这个行为非常有用。在</p> <p>如果您希望listOfInts对于每个实例都是唯一的,那么应该在<strong>init</strong>或类的其他方法中将其定义为self.listOfInts公司在</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何将python输出重定向到python控制台和Windows中的文本文件
9 回答
如何将Python运行时嵌入运行在Windows上的R包中
8 回答
如何将python进程作为另一个Windows us运行
4 回答
如何将Python进程的输出用Python管道传输?
1 回答
如何将Python进程的输出重定向到Rust进程?
2 回答
如何将python连接到Azure云并创建Azure数据工厂
8 回答
如何将Python连接到Db2
8 回答
如何将python连接到IBMDB2?
4 回答
如何将Python连接到microsoftaccess数据库文件?
9 回答
如何将python连接到MySQL服务器
1 回答
如何将Python连接到Node.js?
3 回答
如何将python连接到Oracle Application Express
4 回答
如何将Python连接到PostgreSQL
9 回答
如何将Python连接到Postgres服务器?
3 回答
如何将Python连接到SAS Enterprise Guide(EG)服务器
2 回答
如何将Python连接到Spark会话并保持RDDs的Ali
6 回答
如何将python连接到sqlite3并在上填充多行
3 回答
如何将python连接到使用docker运行的cassandra
7 回答
如何将python退格应用于字符串
4 回答
如何将python逻辑应用到tkinter GUI中?这是一个简单的GET请求程序
4 回答