0

I have a class Neuron in one file by python:

class Neuron:
    def __init__():
       ......
    def other function():
       ......
    def __repr__(self, level=0):
        gap = '\t'*level
        _printable = "{}position {} -- map dimensions {} -- input dataset {} element(s) -- level {} \n".format(
            gap,
            self.position,
            self.__weight_map[0].shape,
            self.input_dataset.shape[0],
            level
        )

        if self.child_map is not None:
            for neuron in self.child_map.neurons.values():
                _printable += neuron.__repr__(level+1)
        return _printable

When I run main function in other file, it calls this class and return the result like that:

> position (0, 0) -- map dimensions (1, 1, 61) -- input dataset 219 element(s) -- level 0
>         position (0, 0) -- map dimensions (2, 4, 61) -- input dataset 28 element(s) -- level 1
>                 position (0, 0) -- map dimensions (2, 4, 61) -- input dataset 0 element(s) -- level 2
>                 position (1, 0) -- map dimensions (2, 4, 61) -- input dataset 10 element(s) -- level 2
>                 position (0, 1) -- map dimensions (2, 4, 61) -- input dataset 4 element(s) -- level 2
>                 ...

Now I want to calculate how many lines in the result, that's to say, in my opinion, how many times the code use this __repr__ function.

I tried to add a var, like cnt_num_times = 0, in __repr__ function, and cnt_num_times += 1, however, it still print lots of 1 in the end, so how to correct it?

4daJKong
  • 1,825
  • 9
  • 21
  • 1
    You need to make sure `cnt_num_times` is defined and initialized _outside_ of the scope of your `__repr__` function. For example, it could be a member field (property) of the `Neuron` class, or a global variable. – Turix Dec 28 '20 at 07:57
  • @Turix Thanks for your reply again. I think you are right. There are two things I am not sure and how to fix: 1 where do I add cnt_num_times = 0, in __init__? 2 how to return this var, because when I add this var behind "return _printable" it still show some other errors – 4daJKong Dec 28 '20 at 08:03
  • Your `__repr__` function is irrelevant to the question. We need to see all the other stuff: how you call it, and how you implement the counter, even if it's unsuccessful. – Mad Physicist Dec 28 '20 at 08:07

1 Answers1

1

Make cnt_num_times a class-variable inside your class, initialize it to 0 either at the declaration or inside __init__.

 class Neuron:
     cnt_num_times = 0

     def __init__():
          ......

     def __repr__(self, level=0):
          Neuron.cnt_num_times += 1

You don't need to return this variable anywhere, you can access it outside the class like Neuron.cnt_num_times as well.

Jarvis
  • 8,494
  • 3
  • 27
  • 58