【发布时间】:2019-03-24 14:01:37
【问题描述】:
我有一个父类 Animal 和子类 Dog。我想为每个创建 1 个实例并打印它们的 count。这是工作代码:
class Animal:
count=0
def __init__(self):
Animal.count+=1
@classmethod
def getCount(cls):
return cls.count
class Dog (Animal):
count=0
def __init__(self):
super().__init__()
Dog.count+=1
a1=Animal()
print(Animal.getCount(),Dog.getCount())
d1=Dog()
print(Animal.getCount(),Dog.getCount())
打印:
1 0
2 1
这是正确的,因为有 2 种动物,但其中只有 1 种是狗。
当我将 count 变量创建为私有 __count 而不更改任何其他代码时,就会出现问题。
class Animal:
__count=0
def __init__(self):
Animal.__count+=1
@classmethod
def getCount(cls):
return cls.__count
class Dog (Animal):
__count=0
def __init__(self):
super().__init__()
Dog.__count+=1
a1=Animal()
print(Animal.getCount(),Dog.getCount())
d1=Dog()
print(Animal.getCount(),Dog.getCount())
现在,它打印:
1 1
2 2
Dog 类似乎只访问 Animal's __count。
你能检测出代码中的错误吗?
【问题讨论】:
-
您使用
@classmethod,因此使用该类的所有内容(您的两个子类)都将使用它。