第一题,要求将输入参数的元素个数显示出来,那就是要用到*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)