-2
class Spam:
    numInstances = 0
    def __init__(self):
        Spam.numInstances = Spam.numInstances + 1
    def printNumInstances():
        print("Number of instances created: %s" % Spam.numInstances)

x = Spam()
x.printNumInstances()

This gives me this error:

Traceback (most recent call last):                                                                                            
  File "main.py", line 9, in <module>                                                                                         
    x.printNumInstances()                                                                                                     
TypeError: printNumInstances() takes 0 positional arguments but 1 was given

I don't understand why.

It should print "1" I guess.

Anwarvic
  • 12,156
  • 4
  • 49
  • 69

3 Answers3

-1

You've declared printNumInstances as a static method, but you're calling it as an instance method.

I think you want Spam.printNumInstances()

(Though it should be a classmethod, if I understand the code correctly, see: What is the difference between @staticmethod and @classmethod?)

Yifan Lu
  • 64
  • 1
-1

You need to add 'self' in the 'printNumInstances()' method.

def printNumInstances(self):
    .....
Cyrus Dsouza
  • 883
  • 7
  • 18
-1

See below

class Spam:
    numInstances = 0
    def __init__(self):
        Spam.numInstances = Spam.numInstances + 1
    def printNumInstances(self):
        print("Number of instances created: %s" % Spam.numInstances)

x = Spam()
x.printNumInstances()
balderman
  • 22,927
  • 7
  • 34
  • 52