栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python继承基础类型(如int)的方法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python继承基础类型(如int)的方法

写一些关于基础类型增强的类时,又想使用这个类的方法,我们会这样写:

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829438.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号