在1个实例而不是2个实例中覆盖内存

2024-05-12 09:41:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为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

Tags: ofthe实例nameworlddomainoutmonitor
2条回答

必须将__init__()方法添加到domain_monitor,否则所有实例将共享相同的nametasks

到目前为止你已经

s1.tasks is s2.tasks
>>>True

添加后:

def __init__(self, name, tasks):
    self.name = name
    self.tasks = tasks

所有实例都将具有单独的属性

class定义中,tasks是一个静态属性,这意味着它将在实例之间共享。应该使用define __init__方法初始化对象属性。例如:

class domain_monitor:
    def __init__(self):
         self.name = ''
         self.tasks = []

顺便说一下,根据PEP8,类名必须在CamelCase中,因此DomainMonitor是更好的选择

相关问题 更多 >