我如何知道 class 生成了多少个实例?
How can I know how many instances were made from a class?
我试过这个程序:
class Test():
def __init__(self):
self.value = 10
print(self.value)
t = Test()
t2 = Test()
我想知道 Test
class.
生成了多少实例
这应该可以完成您正在寻找的工作。休息一下,您可以创建一个文件并打印响应。我只是代表你现在想要的东西:
class Test:
# this is responsible for the count
counter = 0
def __init__(self):
Test.counter += 1
self.id = Test.counter
t = Test()
t2 = Test()
print(Test.counter)
# OUTPUT => 2
为 class 创建一个计数器并在创建新实例时增加它们的想法在大多数情况下都有效。
但是,您应该记住一些方面。如果实例被删除怎么办?没有减少此计数器的机制。为此,您可以使用 __del__
方法,该方法在实例即将被销毁时调用。
class Test:
counter = 0
def __init__(self):
Test.counter += 1
self.id = Test.counter
def __del__(self):
Test.counter -= 1
但有时发现实例被删除时可能会出现问题。如果需要,您可以在 this blog post 中找到更多信息。
我试过这个程序:
class Test():
def __init__(self):
self.value = 10
print(self.value)
t = Test()
t2 = Test()
我想知道 Test
class.
这应该可以完成您正在寻找的工作。休息一下,您可以创建一个文件并打印响应。我只是代表你现在想要的东西:
class Test:
# this is responsible for the count
counter = 0
def __init__(self):
Test.counter += 1
self.id = Test.counter
t = Test()
t2 = Test()
print(Test.counter)
# OUTPUT => 2
为 class 创建一个计数器并在创建新实例时增加它们的想法在大多数情况下都有效。
但是,您应该记住一些方面。如果实例被删除怎么办?没有减少此计数器的机制。为此,您可以使用 __del__
方法,该方法在实例即将被销毁时调用。
class Test:
counter = 0
def __init__(self):
Test.counter += 1
self.id = Test.counter
def __del__(self):
Test.counter -= 1
但有时发现实例被删除时可能会出现问题。如果需要,您可以在 this blog post 中找到更多信息。