-2

Why the following counter does not work, and how to fix it:

class Test():
   def __init__(self):
       self.counter = 0

   def increment(self):
       print counter++

Thank you.

Frank
  • 25
  • 6
  • 1
    When you say does not work, what exactly is the issue? Is there an exception? Does it function incorrectly. I would seem your problem is obvious on this occasion, but its best to give some description of the issue if you don't want the 'closers' to go to work on your question. – Paul Rooney Jan 16 '17 at 22:22
  • BTW what is the purpose of `counter`? As I think you might be needing it as class variable instead of instance variable *(since general usage of counter in class is to count the number objects of class)* – Moinuddin Quadri Jan 16 '17 at 22:22

3 Answers3

1

++ is not valid python

and you need self.counter += 1

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

to use a variable in a class, preface it with self.

class MyCounter():
   def __init__(self, number):
       self.counter = number

   def increment(self):
       self.counter += 1
       print(self.counter)

[IN] >>> counter = MyCounter(5)
[IN] >>> print(counter.increment())
[OUT] >>> 6
lol
  • 481
  • 6
  • 18
0

you can use__init__

class C:
    counter = 0
    def __init__(self):
        C.counter += 1

or

class C:
    counter = 0
    @classmethod
    def __init__(cls):
        cls.counter += 1

or use another method like

class C:
    counter = 0

    @classmethod
    def my_function(cls):
        cls.counter += 1
sahama
  • 669
  • 8
  • 16