一、算术魔法方法的举例

1、加法(__add__)的算术运算调用减法(__sub__)的算术运算,减法(__sub__)的算术运算调用加法(__add__)的算术运算

class New_Init(int):
def __add__(self,other):
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other) >>> a = New_Init('')
>>> b = New_Init()
>>> a+b
-
>>> a-b >>>

2、针对以上需求,现在要求不使用int方法进行运算

class Try_int(int):
def __add__(self,other):
return self+other
def __sub__(self,other):
return self+other >>> a = Try_int(5)
>>> b = Try_int(6)
>>> a+b
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
a+b
File "/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__
return self+other
File "/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__
return self+other
File "/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__
return self+other
[Previous line repeated 990 more times]
RecursionError: maximum recursion depth exceeded #不使用int会使程序一直进行递归运算,导致内存不足
#程序改进

class Try_int(int):
def __add__(self,other):
return int(self)+int(other)
def __sub__(self,other):
return int(self)+int(other) >>> a = Try_int(5)
>>> b = Try_int(6)
>>> a+b
11
>>>

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

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

#a,b是工厂函数(类对象)int的实例对象

>>> a = int('')
>>> b = int('')
>>> a+b
579
>>>

三、类的属性名和方法名绝对不能相同,否则就会报错

首先看以下这段代码是否正确:

class Fool:
def fool(self):
self.fool = 'I LOVE AI'
return self.fool >>> fool = Fool()
>>> fool.fool()
'I LOVE AI'

看起来没有任何错误,其实写成__init__就会报错

class Fool:
def __init__(self):
self.foo = "I LOVE AI"
def foo(self):
return self.fool >>> fool = Fool()
>>> fool.fool()
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
fool.fool()
AttributeError: 'Fool' object has no attribute 'fool'
>>>

#属性名fool和方法名fool绝对不能相同

改进后的代码

class Fool:
def __init__(self):
self.fool = 'I LOVE AI'
def chk(self):
return self.fool >>> f = Fool()
>>> f.chk()
'I LOVE AI'
>>> #属性名fool和方法名ckh不一样

四、写出下列算术运算符对应的魔法方法

运算符                对应的魔法方法              含义

+                  __add__(self,other)             加

-                  __sub__(self,other)             减

*                  __mul__(self,other)             乘

/                  __truediv__(self,other)            除

//                  __foolrdiv__(self,other)            取整除--返回商的整数部分

%                  __mod__(self,other)             取模--返回除法的余数

divmod(a,b)              __divmod__(self,other)

**                   __pow__(self,other[,modulo])            

<<                  __lshift__(self,other)             左移运算符:运算符的各二进位全部左移若干位,由<<右边的数字指定了移动的位数,高位丢弃,地位补0

                                        实例:a<<2输出结果240,二进制解释:1111 0000

>>                  __rshift(self,other)

&                 __and__(self,other)

^                  __xor__(self,other)

|                   __or__(self,other)

五、鸭子类型

在程序设计中,鸭子类型(duck typing)是动态类型的一种风格

在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由当前方法和属性的集合决定。

在鸭子类型中,关注的不是对象的类型本身,而是它是如何使用的

换言之:函数调用了非本类的方法,类的实例对象被用作函数的参数,这就是鸭子类型

class Duck:
def quack(self):
print('呱呱呱')
def feathers(self):
print('这个鸭子拥有灰白灰白的羽毛') class Person:
def quack(self):
print('你才是鸭子你全家是鸭子')
def feathers(self):
print('这个人穿着一件鸭绒大衣') def in_the_forest(duck):
duck.quack()
duck.feathers() def game():
donald = Duck()
join = Person() in_the_forest(donald)
in_the_forest(join) game() 呱呱呱
这个鸭子拥有灰白灰白的羽毛
你才是鸭子你全家是鸭子
这个人穿着一件鸭绒大衣
>>>

代码含义:

in_the_forest()函数对参数duck只有一个要求:就是实现了quack()和feathers()方法,然而Duck类和Person()类都实现了quack()和feathers()方法,因此他们的实例对象donald和join都可以用作
in_the_forest()的参数。这就是鸭子类型

六、

1、在python中,两个字符串相加会自动拼接字符串,但两个字符串相减会抛出异常。因此,现在我们要求定义一个Nstr类,支持字符串的相减操作:A-B,从A中去除所有B的字符串

>>> a = ''
>>> b = ''
>>> a+b
''
>>> a-b
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>

采用Nstr类

class Nstr(str):
def __sub__(self,other):
return self.replace(other,'') >>> a = Nstr('')
>>> b = Nstr('')
>>> a-b
''

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

需要用__lshift__和__rshift__魔法方法即可

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 AI!!!')
>>> a<<3
'ove AI!!!I l'
>>> a>>3
'!!!I love AI'
>>>

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

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

【Python042--魔法方法:算术运算】的更多相关文章

  1. 魔法方法:算术运算 - 零基础入门学习Python042

    魔法方法:算术运算 让编程改变世界 Change the world by program 我现在重新提一个名词:工厂函数,不知道大家还有没有印象?我们在老早前就提到过Ta,由于那时候我们还没有学习类 ...

  2. python_魔法方法(二):算术运算

    python2.2之后,对类和类型做了同意,将int().float().str().list().touple()这些BIF转换为工厂函数 >>> type(len) <cl ...

  3. python类与对象各个算数运算魔法方法总结

    1.python类与对象各个算术运算魔法方法总结: 2.各个魔法方法应用举例: 3.实例训练: (1)我们都知道在 Python 中,两个字符串相加会自动拼接字符串,但遗憾的是两个字符串相减却抛出异常 ...

  4. PHP的魔法方法__set() __get()

    php的魔法方法__set()与__get() Tags: PHP 我们先来看看官方的文档如何定义他们的: public void __set(string $name, mixed $value); ...

  5. python进阶(四)---需要了解的魔法方法

    以下内容,源于个人理解所得,纯属臆测,爱信不信:-D.欢迎大家留言讨论指正. 1.__new__魔法方法: 原型:__new__(cls, *args, **kwargs) 说明:__new__魔法方 ...

  6. Python中的魔法方法

    1.什么是魔法方法? 魔法方法就是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一 ...

  7. Python的魔法方法 .

    基本行为和属性 __init__(self[,....])构造函数 . 在实例化对象的时候会自动运行 __del__(self)析构函数 . 在对象被回收机制回收的时候会被调用 __str__(sel ...

  8. 《Python基础教程(第二版)》学习笔记 -> 第九章 魔法方法、属性和迭代器

    准备工作 >>> class NewStyle(object): more_code_here >>> class OldStyle: more_code_here ...

  9. python 魔法方法

    I am not a creator, I just a porter. Note: Everything is object in python. 对于Python来说一切都是对象,也就是函数的参数 ...

  10. Python学习笔记:06魔法方法和迭代器

    魔法方法,属性和迭代器 新式类 通过赋值语句__metaclass=true或者class NewStyle(object)继承内建类object,可以表明是新式类. 构造方法 对象被创建后,会立即调 ...

随机推荐

  1. opencv-resize()放缩函数简介

    主要介绍函数resize(); 图像缩放的效果图如下: 主程序代码及函数解释如下所示: /******************************************************* ...

  2. 37.js----浅谈js原型的理解

    浅谈Js原型的理解 一.js中的原型毫无疑问一个难点,学习如果不深入很容易就晕了!    在参考了多方面的资料后,发现解释都太过专业,对于很多还没有接触过面向对象    语言的小白来说,有理解不了里面 ...

  3. OBV15 案例5,上M10拉高出货

  4. Some Useful Resources for the Future Usage

    并发编程 http://ifeve.com/ 美国各州 http://114.xixik.com/usa-stats/ 美国各州邮编zip code -> https://www.douban. ...

  5. pymysql 数据库操控

    模块安装 pip install pymysql 执行sql语句 import pymysql #添加数据 conn = pymysql.connect(host='127.0.0.1', port= ...

  6. turtle库基础练习

    1.画一组同切圆 import turtle turtle.circle(10) turtle.circle(20) turtle.circle(30) turtle.circle(40) turtl ...

  7. linux 命令杂集

    [1]查找日志中某个字符串XXXX tail -f  日志文件名 |  grep  "XXXX" [2]linux抓包命令 tcpdump -i XXX -A  ip xxx.xx ...

  8. Impala 学习

    Impala 基础知识介绍与学习,参考文章: Impala-大数据时代快速SQL引擎 https://blog.csdn.net/kangkangwanwan/article/details/7865 ...

  9. CSS, JavaScript 压缩, 美化, 加密, 解密

    CSS, JavaScript 压缩, 美化, 加密, 解密 JS压缩, CSS压缩, javascript compress, js在线压缩,javascript在线压缩,css在线压缩,YUI C ...

  10. OAuth2.0 知多少(好)

    https://www.cnblogs.com/sheng-jie/p/6564520.html 简书集成的社交登录,大大简化了我们的注册登录流程,真是一号在手上网无忧啊.这看似简单的集成,但背后的技 ...