这是spam.py:
class Spam:
numInstances = 0
def __init__(self):
Spam.numIntances = Spam.numInstances + 1
def printNumInstances():
print("Number of instances created: %s" % Spam.numInstances)
这是另一个文件。py:
from spam import Spam
a = Spam()
b = Spam()
c = Spam()
Spam.printNumInstances()
a.printNumInstances()
为什么打印“创建的实例数:0”而不是“创建的实例数:3”?
答案 0 :(得分:0)
您遇到了一些错别字,printNumInstances
应该是一种课堂方法。
class Spam:
numInstances = 0
def __init__(self):
Spam.numInstances = Spam.numInstances + 1
@classmethod
def printNumInstances(cls):
print("Number of instances created: %s" % cls.numInstances)
a = Spam()
b = Spam()
c = Spam()
Spam.printNumInstances()
a.printNumInstances()
输出:
Number of instances created: 3
Number of instances created: 3