我试图为s1和s2创建两个实例,但是内存被写入了两次。 我得到:
Out of the World
Book: Decision Procedure
=========================================
Out of the World
Book: Decision Procedure
instead of
Out of the World
=========================================
Book: Decision Procedure
How is this so?
我创建了一个类,如下所示:
class domain_monitor:
name = '';
tasks = [];
我开始填充以下实例:
s1 = domain_monitor();
s1.name = "s1";
s1.tasks.append("Out of the World");
s2 = domain_monitor();
s2.name = "s2";
s2.tasks.append("Book: Decision Procedure");
我打印输出如下:
for v in s1.tasks: #
print v
print " ========================================= "
for v in s2.tasks: #
print v
必须将
__init__()
方法添加到domain_monitor
,否则所有实例将共享相同的name
和tasks
到目前为止你已经
添加后:
所有实例都将具有单独的属性
在
class
定义中,tasks
是一个静态属性,这意味着它将在实例之间共享。应该使用define__init__
方法初始化对象属性。例如:顺便说一下,根据PEP8,类名必须在
CamelCase
中,因此DomainMonitor
是更好的选择相关问题 更多 >
编程相关推荐