【Python042--魔法方法:算术运算】
一、算术魔法方法的举例
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--魔法方法:算术运算】的更多相关文章
- 魔法方法:算术运算 - 零基础入门学习Python042
魔法方法:算术运算 让编程改变世界 Change the world by program 我现在重新提一个名词:工厂函数,不知道大家还有没有印象?我们在老早前就提到过Ta,由于那时候我们还没有学习类 ...
- python_魔法方法(二):算术运算
python2.2之后,对类和类型做了同意,将int().float().str().list().touple()这些BIF转换为工厂函数 >>> type(len) <cl ...
- python类与对象各个算数运算魔法方法总结
1.python类与对象各个算术运算魔法方法总结: 2.各个魔法方法应用举例: 3.实例训练: (1)我们都知道在 Python 中,两个字符串相加会自动拼接字符串,但遗憾的是两个字符串相减却抛出异常 ...
- PHP的魔法方法__set() __get()
php的魔法方法__set()与__get() Tags: PHP 我们先来看看官方的文档如何定义他们的: public void __set(string $name, mixed $value); ...
- python进阶(四)---需要了解的魔法方法
以下内容,源于个人理解所得,纯属臆测,爱信不信:-D.欢迎大家留言讨论指正. 1.__new__魔法方法: 原型:__new__(cls, *args, **kwargs) 说明:__new__魔法方 ...
- Python中的魔法方法
1.什么是魔法方法? 魔法方法就是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一 ...
- Python的魔法方法 .
基本行为和属性 __init__(self[,....])构造函数 . 在实例化对象的时候会自动运行 __del__(self)析构函数 . 在对象被回收机制回收的时候会被调用 __str__(sel ...
- 《Python基础教程(第二版)》学习笔记 -> 第九章 魔法方法、属性和迭代器
准备工作 >>> class NewStyle(object): more_code_here >>> class OldStyle: more_code_here ...
- python 魔法方法
I am not a creator, I just a porter. Note: Everything is object in python. 对于Python来说一切都是对象,也就是函数的参数 ...
- Python学习笔记:06魔法方法和迭代器
魔法方法,属性和迭代器 新式类 通过赋值语句__metaclass=true或者class NewStyle(object)继承内建类object,可以表明是新式类. 构造方法 对象被创建后,会立即调 ...
随机推荐
- MyBatis基础入门《八》查询参数传入Map
MyBatis基础入门<八>查询参数传入Map 描述: 在执行select查询数据的时候,方法传入的参数是java.util.Map类型. 接口方法: xml文件 注意: 书写SQL语句的 ...
- python中的lxml模块
Python中自带了XML的模块,但是性能不太好,相比之下,LXML增加了很多实用的功能. lxml中主要有两部分, 1) etree,主要可以用来解析XML字符串, 内部有两个对象,etree._E ...
- while练习题
# 1. 使用while循环输出1 2 3 4 5 6 8 9 10count = 1while count <= 10: if count == 7: count += 1 continue ...
- html5-select和datalist元素
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8&qu ...
- sitecore系列教程之营销人员和技术人员如何策划与消费者的对话以提升体验?
“每次良好的交谈都要从良好的倾听开始.” - 未知 你是如何听取网站访问者的?你是在倾听还是只是回复? 拥有内容管理系统只是良好网站战略的一个要素.毕竟,内容必须是动态的,及时的和相关的. 当网站访问 ...
- Java集合-----Set详解
Set是没有重复元素的集合,是无序的 1.HashSet HashSet它是线程不安全的 HashSet常用方法: add(E element) 将指定的元素添加到此集合(如果尚未存 ...
- 设计模式之Observer(观察者)(转)
Java深入到一定程度,就不可避免的碰到设计模式(design pattern)这一概念,了解设计模式,将使自己对java中的接口或抽象类应用有更深的理解.设计模式在java的中型系统中应用广泛,遵循 ...
- flask 的类中间件
需求 : 如果登陆了,就可以访问 index 和 home 页面,如果没登录就跳转到 login 登录 要怎么解决呢, session 对, 用 session 除了 Login 函数之外的所有函数里 ...
- linux学习---ps、kill
一.ps 查看进程 ps 为我们提供了进程的一次性的查看,它所提供的查看结果并不动态连续的:如果想对进程时间监控,应该用 top 工具 linux上进程有5种状态: 1. 运行(正在运行或 ...
- GoldenGate 12.2抽取Oracle 12c多租户配置过程
linux下安装12c 重启linux之后,dbca PDB/CDB使用 SQL> select instance_name from v$instance; INSTANCE_NAME --- ...