美文网首页python入门
python第42课练习—魔法方法:算术运算

python第42课练习—魔法方法:算术运算

作者: YoYoYoo | 来源:发表于2019-06-17 11:04 被阅读0次

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

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

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

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

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

3、下边的代码有问题吗?(运行起来似乎没出错呀)

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#19>", line 1, in <module>
    foo.foo()
TypeError: 'str' object is not callable

4、写出下列运算符对应的魔法方法。

运算符 对应的魔法方法
+ __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)

5、以下代码说明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)风格。

练习

1、我们都知道在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,'')

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

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

答:只需要重载__lshift__和__rshift__魔法方法即可。

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

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

>>> 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

相关文章

  • python第42课练习—魔法方法:算术运算

    1、自Python2.2以后,对类和类型进行了统一,做法就是将int()、float()、str()、list()...

  • Python 学习笔记 - 运算符

    Python 运算符 Python 运算符类型 Python 支持如下几种运算符: 算术运算符(Arithmeti...

  • 【Python一级】运算符

    在python一级考试中,主要运用到算术运算符、比较运算符、逻辑运算符 算术运算符 算术运算符算术运算符与数值一起...

  • python语句

    1. python运算符 算术运算符:+ - * / // % ** 比较运算符:> >=...

  • Python基础知识1:运算符

    一、算术运算符 算术运算符是 运算符的一种 是完成基本的算术运算使用的符号,用来处理四则运算 在Python中 *...

  • 第3章 - 运算符 和 基础函数

    第3章 - 运算符 和 基础函数 3.1 运算符 Python支持一下7种运算符: 算术运算符 比较(关系)运算符...

  • Python运算符

    Python运算符主要包括算术、比较、赋值、逻辑、成员、身份运算符等等。 一、算术运算符: 1、加减乘除:+-*/...

  • Python基础-4·运算符

    一、运算符分类 Python 中所支持的运算符: 算术运算符 比较运算符 逻辑运算符 二、算术运算符 算数运算符是...

  • Python基础学习笔记(二)运算符

    本节介绍Python中运算符基础知识: 一、算术运算符 例题:输入一个三位数,返回每个位置的数字方法一(通过算术运...

  • 005运算符

    python支持以下几种运算符 ·算术运算符 ·赋值运算符 ·复合赋值运算符

网友评论

    本文标题:python第42课练习—魔法方法:算术运算

    本文链接:https://www.haomeiwen.com/subject/lreofctx.html