Home > database >  Python class __str__ created and destroyed object
Python class __str__ created and destroyed object

Time:10-31

How to use __str__ instead of #print?

Here is the code:

from itertools import count


class Bug:

  _counter = 0

  def __init__(self):
      Bug._counter  = 1
      self.id = Bug._counter
      #print("Obiekt stworzony:", self.id, self._counter)

  def __del__(self):
      Bug._counter -= 1
      self.id = Bug._counter
      #print("Obiekt unicestwiony:", self.id, self._counter)

  def __str__ (self):
      return 


bugs = []
for i in range(100):
    bugs.append(Bug())
    print(bugs[-1])

I wanted to print id and number of processes (counter) for __init__ and __del__ using with __str__.

CodePudding user response:

If I understand the problem correctly then I would suggest this:

class Bug:
    _counter = 0 # number of Bug instances
    _ids = [] # list of reusable IDs

    def __init__(self):
        Bug._counter  = 1 # increment number of Bug instances
        # reuse previously deleted ID if available otherwise use Bug._counter
        self._id = Bug._counter if len(Bug._ids) == 0 else Bug._ids.pop(0)

    def __del__(self):
        Bug._counter -= 1 # decrement number of Bug instances
        # make this instance's ID available for reuse
        Bug._ids.append(self._id)

    def __repr__(self):
        return f'{Bug._counter=} {self._id=}'

    def __str__ (self):
        return f'Bug count={Bug._counter} ID={self._id}'

# create list with 20 Bugs
bugs = [Bug() for _ in range(20)]
# print last Bug in list
print(bugs[-1])
# delete a bug
del bugs[10]
# print last Bug in list
print(bugs[-1])
# add a new Bug to the list
bugs.append(Bug())
# print last Bug in list
print(bugs[-1])

Output:

Bug count=20 ID=20
Bug count=19 ID=20
Bug count=20 ID=11

Note:

The Bug with ID == 11 (i.e., subscript 10 in the list) was deleted. When we added a new Bug the ID was reused

  • Related