Python 小甲鱼教程 课后练习43
来源:互联网 发布:a4不干胶打印软件 编辑:程序博客网 时间:2024/04/28 19:42
第一题,要求将输入参数的元素个数显示出来,那就是要用到*argv关键字参数了
自己的答案
class C:
def __init__(self,*argv):
if not argv:
print ('no input')
else:
print ('There are %d parameters,and they are '%len(argv),end='')
for i in argv:
print (i,end=' ')
c=C(1,2,3,4,5)
第二题是对重写比较操作符的魔法方法,要求比较的标准是单词长度
class Word(str):
def __lt__(self,other):
return len(self)<len(other)
def __le__(self,other):
return len(self)<=len(other)
def __gt__(self,other):
return len(self)>len(other)
def __ge__(self,other):
return len(self)>=len(other)
然后对于加分的那道题,是看答案的,要求重写__new__方法,来实现,他实际上是通过切片的原理来实现的,我一开始还在想着通过while循环是否可以实现,在遇到空格以后break,但是好像没有办法,还是去论坛上问一下
他重写的__new__是如下的,有点高级,自己想不到这样的方法...
def __new__(cls, word):
# 注意我们必须要用到 __new__ 方法,因为 str 是不可变类型
# 所以我们必须在创建的时候将它初始化
if ' ' in word:
print "Value contains spaces. Truncating to first space."
word = word[:word.index(' ')] #单词是第一个空格之前的所有字符
return str.__new__(cls, word)
- Python 小甲鱼教程 课后练习43
- Python 小甲鱼教程 课后练习20
- Python 小甲鱼教程 课后练习29
- Python 小甲鱼教程 课后练习30
- Python 小甲鱼教程 课后练习39
- Python 小甲鱼教程 课后练习42
- Python 小甲鱼教程 课后练习44
- Python 小甲鱼教程 课后练习25 关于字典
- Python 小甲鱼教程 课后练习31 pickle模块
- Python 小甲鱼教程 课后练习33 异常处理
- Python 小甲鱼教程 课后练习30 番外篇_需要谨记!!!
- Python 小甲鱼教程 Easygui 练习
- Python 小甲鱼教程 Easygui 篇
- Python 小甲鱼教程 属性访问
- 小甲鱼教程-文字小游戏-界面框-Easygui练习
- 小甲鱼学python
- 小甲鱼学python
- 小甲鱼学python
- setup lang
- 从问题看本质:socket到底是什么?
- HDU1425 sort
- 为什么 Archlinux 不适合服务器使用
- RMQ with Shifts
- Python 小甲鱼教程 课后练习43
- eclipse-android配置maven,tomcat,mysql及其sqlyog
- linux下使用过程中的一些列解决方法
- 操作系统的基本功能
- 最强日期正则表达式
- 【Effective C++读书笔记】篇十(条款25)
- ERROR org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler - Exception
- Mac charles 配置ssl
- 4、字符串