(标答出处: 鱼C论坛)
《零基础入门学习Python》
测试题:
答:工厂函数其实就是一个类对象,当你调用他们的时候实际上就是创建了一个对象。 例:
a = int ('123')
print (a)
b = int ('345')
print (b)
print (a+b)
运行结果
答:当实例对象进行假发操作时,会自动调用 __ add __ 的魔法方法。
答 :类的属性名和方法名绝对不能相同。 如果如同下面这样写,那么问题就出现了。
class Foo :
def __init__ (self) :
self.foo = 'I love you'
def foo(self) :
return self.foo
foo = Foo()
foo.foo()
运行结果:
运算符 | 对应的魔法方法 |
---|---|
+ | __ add __(self,other) |
- | __ sub __(self,other) |
* | __ mul __(self,other) |
/ | __ truediv__(self,other) |
// | __ floordiv__(self,other) |
% | __ mod __(self,other) |
divmod(a,b) | divmod(self,other) |
** | __ pow __(self, other[, modulo]) |
<< | __ lshiift __(self,other) |
>> | __ rshift __(self,other) |
& | __ and __(self, other) |
^ | __ xor __(self, other) |
I | __ or __(self, other) |
答:说明python支持鸭子类型(duck typing)风格。
动动手
class Nstr (str):
def __sub__ (self,other):
return self.replace(other,'')
a = Nstr ('I love Fishc yeyeye')
b = Nstr ('ye')
print (a-b)
运行结果:
class Nstr (str):
def __lshift__ (self,other) :
return self[other:] +self[:other]
def __rshift__ (self,other) :
return self[:-other]+self[-other:]
a = Nstr ('I love Fishc yeyeye!')
print (a<<3)
print (a>>3)
运行结果:
class Nstr (str):
"""加"""
def __add__ (self,other) :
total1 = 0
total2 = 0
for each in self :
total1 = total1 + ord (each)
self = total1
for each in other :
total2 = total2 + ord (each)
other = total2
return self.__add__(other)
"""减"""
def __sub__ (self,other) :
total1 = 0
total2 = 0
for each in self :
total1 = total1 + ord (each)
self = total1
for each in other :
total2 = total2 + ord (each)
other = total2
return self.__sub__(other)
"""乘"""
def __mul__ (self,other) :
total1 = 0
total2 = 0
for each in self :
total1 = total1 + ord (each)
self = total1
for each in other :
total2 = total2 + ord (each)
other = total2
return self.__mul__ (other)
"""除"""
def __truediv__ (self,other) :
total1 = 0
total2 = 0
for each in self :
total1 = total1 + ord (each)
self = total1
for each in other :
total2 = total2 + ord (each)
other = total2
return self.__truediv__(other)
"""整除"""
def __floordiv__ (self,other) :
total1 = 0
total2 = 0
for each in self :
total1 = total1 + ord (each)
self = total1
for each in other :
total2 = total2 + ord (each)
other = total2
return self.__floordiv__(other)
a = Nstr ('I love Xmy !')
b = Nstr ('love')
print (a+b)
print (a-b)
print (a*b)
print (a/b)
print (a//b)
运行结果:
或者如下:
class Nstr (str):
def __init__ (self,arg = '') :
if isinstance (arg , str ) :
self.total = 0
for each in arg :
self.total += ord(each)
else :
print ('参数错误!')
"""加"""
def __add__ (self,other) :
return self.total + other.total
"""减"""
def __sub__ (self,other) :
return self.total - other.total
"""乘"""
def __mul__ (self,other) :
return self.total * other.total
"""除"""
def __truediv__ (self,other) :
return self.total / other.total
"""整除"""
def __floordiv__ (self,other) :
return self.total // other.total
a = Nstr ('FishC')
b = Nstr ('love')
print (a+b)
print (a-b)
print (a*b)
print (a/b)
print (a//b)