鱼C论坛

 找回密码
 立即注册
查看: 2272|回复: 2

python 41讲 课后题最后一题 ,为什么print可以直接打印,不用实例化。

[复制链接]
发表于 2016-9-29 14:22:14 | 显示全部楼层 |阅读模式
50鱼币
本帖最后由 wow7jiao 于 2016-9-29 21:12 编辑

>>> print(Nint(123))  
123
>>> print(Nint(1.5))#如何过滤掉小数点的,int?
1
>>> print(Nint('A'))
65
>>> print(Nint('FishC'))
461


class Nint(int):  #这个int就是取整型的意思吗?#int是哪课讲解的?
        def __new__(cls, arg=0):#用__new__后就不需要实例化?可以直接调用打印?
                if isinstance(arg, str):  #str为什么是一个类?  
                        total = 0
                        for each in arg:
                                total += ord(each)
                        arg = total
                return int.__new__(cls, arg)


最佳答案

查看完整内容

Nint 继承自 int ,而 int 直接截取整数部分。 int(1.1) # 1 int(1.9) # 还是 1 int,str,等 都是内置的基本类型, python中,类 本身也是 对象 参考: https://docs.python.org/3/library/stdtypes.html Nint(1.5) 类名称后面加 () 的含义就是实例化
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-9-29 14:22:15 | 显示全部楼层
>>> print(Nint(1.5))#如何过滤掉小数点的,int?

Nint 继承自 int ,而 int 直接截取整数部分。
int(1.1) # 1
int(1.9) # 还是 1


class Nint(int):  #这个int就是取整型的意思吗?#int是哪课讲解的?
                if isinstance(arg, str):  #str为什么是一个类?  

int,str,等 都是内置的基本类型,
python中,类 本身也是 对象
参考:
https://docs.python.org/3/library/stdtypes.html

为什么print可以直接打印
        def __new__(cls, arg=0):#用__new__后就不需要实例化?可以直接调用打印?

Nint(1.5)
类名称后面加 () 的含义就是实例化
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-9-29 18:46:40 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-23 02:13

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表