垃圾邮件类别:numInstances = 0 def __init __(self):

时间:2019-10-07 13:43:21

标签: python

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()

这给了我这个错误:

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

我不明白为什么。

我猜它应该打印“ 1”。

3 个答案:

答案 0 :(得分:-2)

您已将printNumInstances声明为静态方法,但您将其称为实例方法。

我认为您想要Spam.printNumInstances()

(尽管它应该是一种类方法,但如果我正确理解代码,请参阅:What is the difference between @staticmethod and @classmethod?

答案 1 :(得分:-2)

您需要在'printNumInstances()'方法中添加'self'。

def printNumInstances(self):
    .....

答案 2 :(得分:-2)

见下文

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()