0

I tried to create 2 instances for s1 and s2, but the memory get written twice. I get:

     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?

I created a class as following:

     class domain_monitor:
         name = '';
         tasks = [];

I started populating the instances as following:

     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");

I print the output as following:

     for v in s1.tasks:   # 
       print v
     print " ========================================= "
     for v in s2.tasks:   # 
       print v
Ursa Major
  • 851
  • 7
  • 25
  • 47

2 Answers2

2

You have to add __init__() method to domain_monitor, otherwise all you instances will share the same name and tasks.

So far you have

s1.tasks is s2.tasks
>>>True

After you add:

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

All instances will have separate properties.

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
1

In your class definition tasks is a static property, meaning that it will be shared across instances. You should use define a __init__ method to initialize object properties. For example:

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

By the way, class names must be in CamelCase according to PEP8, so DomainMonitor would be a better choice.

Selcuk
  • 57,004
  • 12
  • 102
  • 110