写一些关于基础类型增强的类时,又想使用这个类的方法,我们会这样写:
class Test(int):
pass
但是,当写具体的方法时,我们的继承要不同于其他:
class Test(int):
def __new__(cls, num=0): # 注意是new方法
return int.__new__(cls, num)
而__new__
函数比__init__
函数早执行,我们就可以继承int
类。
class Integer(int):
def __init__(self, num=0):
self.num = num
def __new__(cls, num: Optional[Union[int, float, str, bool]] = 0):
return int.__new__(cls, num)
最后贴一个例子,给int类添加一个判断是否是素数的功能:
import math
from typing import Optional, Union
class Integer(int):
def __init__(self, num: Optional[Union[int, float, str, bool]] = 0):
self.num = num
def __new__(cls, num: Optional[Union[int, float, str, bool]] = 0):
return int.__new__(cls, num)
def is_prime(self):
n = self.num
if n < 1:
raise ValueError('The number must be a positive integer')
if n == 1:
return False
for i in {2, 3, 5, 7, 9, 11, 13, 17, 23}:
if n == i:
return True
if n % i == 0:
return False
for i in range(2, math.ceil(math.sqrt(n))):
if n % i == 0:
return False
return True