ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

第042讲:魔法方法:算术运算 | 课后测试题及答案

2022-01-20 11:58:19  阅读:182  来源: 互联网

标签:__ foo 测试题 self other 课后 total 042 def


测试题:

0. 自 Python2.2 以后,对类和类型进行了统一,做法就是将 int()、float()、str()、list()、tuple() 这些 BIF 转换为工厂函数。请问所谓的工厂函数,其实是什么原理?

答:工厂函数,其实就是一个类对象。当你调用他们的时候,事实上就是创建一个相应的实例对象。

# a 和 b 是工厂函数(类对象) int 的实例对象
>>> a = int('123')
>>> b = int('345')
>>> a + b
468

1. 当实例对象进行加法操作时,会自动调用什么魔法方法?

答:对象 a 和 b 相加时(a + b),Python 会自动根据对象 a 的 add 魔法方法进行加法操作。

2. 下边代码有问题吗?(运行起来似乎没出错的说_

class Foo:
        def foo(self):
                self.foo = "I love FishC.com!"
                return self.foo

>>> foo = Foo()
>>> foo.foo()
'I love FishC.com!'

答:这绝对是一个温柔的陷阱,这种BUG比较难以排查,所以一定要注意:类的属性名和方法名绝对不能相同!如果代码这么写,就会有一个难以排查的BUG出现了:

class Foo:
        def __init__(self):
                self.foo = "I love FishC.com!"
        def foo(self):
                return self.foo

>>> foo = Foo()
>>> foo.foo()
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    foo.foo()
TypeError: 'str' object is not callable

3. 写出下列算术运算符对应的魔法方法:

运算符对应的魔法方法
+__ add __(self, other)
-__ sub __(self, other)
*__ mul __(self, other)
/__ truediv __(self, other)
//__ floordiv __(self, other)
%__ mod __(self, other)
divmod(a, b)__ divmod __(a, b)
**__ pow__(self, other[, modulo])
<<__ lshift__(self, other)
>>__ rshift__(self, other)
&__ and__(self, other)
^__ xor__(self, other)
|__ or__(self, other)

4. 以下代码说明 Python 支持什么风格?

def calc(a, b, c):
        return (a + b) * c

>>> a = calc(1, 2, 3)
>>> b = calc([1, 2, 3], [4, 5, 6], 2)
>>> c = calc('love', 'FishC', 3)
>>> print(a)
9
>>> print(b)
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
>>> print(c)
loveFishCloveFishCloveFishC

答:说明 Python 支持鸭子类型(duck typing)风格。

动动手:

0. 我们都知道在 Python 中,两个字符串相加会自动拼接字符串,但遗憾的是两个字符串相减却抛出异常。因此,现在我们要求定义一个 Nstr 类,支持字符串的相减操作:A – B,从 A 中去除所有 B 的子字符串。

示例:

>>> a = Nstr('I love FishC.com!iiiiiiii')
>>> b = Nstr('i')
>>> a - b
'I love FshC.com!'

答:只需要重载 sub 魔法方法即可。

class Nstr(str):
    def __sub__(self, other):
        return self.replace(other, '')

1. 移位操作符是应用于二进制操作数的,现在需要你定义一个新的类 Nstr,也支持移位操作符的运算:

>>> a = Nstr('I love FishC.com!')
>>> a << 3
'ove FishC.com!I l'
>>> a >> 3
'om!I love FishC.c'

答:只需要重载 lshiftrshift 魔法方法即可。

class Nstr(str):
    def __lshift__(self, other):
        return self[other:] + self[:other]

    def __rshift__(self, other):
        return self[-other:] + self[:-other]

2. 定义一个类 Nstr,当该类的实例对象间发生的加、减、乘、除运算时,将该对象的所有字符串的 ASCII 码之和进行计算:

>>> a = Nstr('FishC')
>>> b = Nstr('love')
>>> a + b
899
>>> a - b
23
>>> a * b
201918
>>> a / b
1.052511415525114
>>> a // b
1
class Nstr:
    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

class Nstr(int):
    def __new__(cls, arg=0):
        if isinstance(arg, str):
            total = 0
            for each in arg:
                total += ord(each)
            arg = total
        return int.__new__(cls, arg)

标签:__,foo,测试题,self,other,课后,total,042,def
来源: https://blog.csdn.net/lemogate/article/details/122597824

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有