您可能希望生成int的一个子类,它的行为类似于int,但有一些额外的行为。在
为此,可以使用继承:>>> class CountFromBy(int):
... pass
现在,当您编写c = CountFromBy()时,它是一个CountFromBy实例,也是一个int实例,因此:
^{pr2}$
到目前为止,您还没有添加任何新的行为,但是如果您想这样做,只需添加方法:>>> class CountFromBy(int):
... def squared(self):
... return CountFromBy(self * self)
>>> c = CountFromBy(3)
>>> c
3
>>> c.squared()
9
但是如果您想添加increase()方法,就有一个大问题:int值是不可变的。因为CountFromBy值是int值,所以它们也是不可变的。不可能用这种方式编写类。在
您可能正在寻找一个类,它使用一个int,而不是是一个的类。为此,不使用继承,只需创建一个成员:
^{4}$
如果希望它打印出它的number值,可以给它一个str方法:>>> class CountFromBy:
... def __init__(self):
... self.number = 0
... def __repr__(self):
... return f'CountFromBy({self.number})'
... def __str__(self):
... return str(self.number)
>>> c = CountFromBy()
>>> c
CountFromBy(0)
>>> print(c)
0
现在,您可以添加increase方法,它只是将self.number替换为一个新值:>>> class CountFromBy:
... def __init__(self):
... self.number = 0
... def __repr__(self):
... return f'CountFromBy({self.number})'
... def __str__(self):
... return str(self.number)
... def increase(self):
... self.number = self.number + 1
>>> c = CountFromBy()
>>> c.increase()
>>> c.increase()
>>> c.increase()
>>> print(c)
3
最后,您可能正在寻找两个世界中的最好的东西,即尽可能像int而不是实际的int来存储。这就像标准库中的^{}和朋友,所以您可以查看the source for those classes。正如你所看到的,这有点复杂,所以你可能还不想尝试。另外,你必须决定“尽可能像一个int”的行为意味着什么,同时又是可变的。在