一:callables

  callables使类实例能够像函数一样被调用
  如果类需要一个函数型接口这时用callable,最好继承自abc.Callable,这样有些检查机制并且一看就知道此类的目的是callable对象
如果类需要有‘记忆’功能,使用callable是非常方便的相对于函数而言,callable语法什么的就要复杂多了,这也是其主要的缺点:
    def x(args):
body
转化为callable对象:
class X(collections.abc.callable):
def __call__(self, args):
body
x= X()   1:计算x^y
 import collections.abc                          #注,完全可以不引入cleection.abc,引入是为了能够做一些错误检查
class Power1( collections.abc.Callable ):
def __call__( self, x, n ):
p= 1
for i in range(n):
p *= x
return p power= Power1()
>>> power( 2, 0 ) #像函数一样调用实例
1
>>> power( 2, 1 )
2
>>> power( 2, 2 )
4
>>> power( 2, 10 )
1024 # 提升性能:上面是O(n),用递归改进为O(logn)
class Power4( abc.Callable ):
def __call__( self, x, n ):
if n == 0:
return 1
elif n % 2 == 1:
return self.__call__(x, n-1)*x
else:
t= self.__call__(x, n//2)
return t*t pow4= Power4() # 再次提升性能,使用记忆功能【注:可以{(2,4):16,... }
class Power5( collections.abc.Callable ):
def __init__( self ):
self.memo = {}
def __call__( self, x, n ):
if (x,n) not in self.memo:
if n == 0:
self.memo[x,n]= 1
elif n % 2 == 1:
self.memo[x,n]= self.__call__(x, n-1) * x
elif n % 2 == 0:
t= self.__call__(x, n//2)
self.memo[x,n]= t*t
else:
raise Exception("Logic Error")
return self.memo[x,n] pow5= Power5() # 再次改进,python库自带了一个记忆装饰器,可以使用这个从而不不用自定义callable对象
from functools import lru_cache
@lru_cache(None)
def pow6( x, n ):
if n == 0:
return 1
elif n % 2 == 1:
return pow6(x, n-1)*x
else:
t= pow6(x, n//2)
return t*t
# Previous requests are stored in a memoization cache. The requests are
# tracked in the cache, and the size is limited. The idea behind an LRU cache is that
# the most recently made requests are kept and the least recently made requests are quietly purged.

callable试例1

   2:赌注翻倍:综合运用callables,输家翻倍赌注政策:每输一次后赌注就加倍直到赢了后回归原本赌注

 class BettingMartingale( BettingStrategy ):
def __init__( self ):
self._win= 0
self._loss= 0
self.stage= 1
@property
def win(self):
return self._win
@win.setter
def win(self, value):
self._win = value
self.stage= 1
@property
def loss(self):
return self._loss
@loss.setter
def loss(self, value):
self._loss = value
self.stage *= 2 def __call__( self ):
return self.stage >>> bet= BettingMartingale()
>>> bet()
1
>>> bet.win += 1
>>> bet()
1
>>> bet.loss += 1
>>> bet()
2 # property的使用使类的定义显得冗杂,实际上我们只关心setters,所以我们用__setattr__来改进上述版本
class BettingMartingale2( BettingStrategy ):
def __init__( self ):
self.win= 0
self.loss= 0
self.stage= 1
def __setattr__( self, name, value ):
if name == 'win':
self.stage = 1
elif name == 'loss':
self.stage *= 2
super().__setattr__( name, value )
def __call__( self ):
return self.stage

callable示例2

二:context
  A context is generally used to acquire/release, open/close, and lock/unlock types of operation pairs.
  Most of the examples are file I/O related, and most of the file-like objects in Python are already proper context managers.
  1:一些context
   1:最常见的是用在文件的,with语句创建
   2:decimal context:decimal是一个模块,常用于一些对于精度要求比较严格的计算,其本身运行在一个context中,通过改context可以对全局的计算产生影响
   3:还有一些context,主要都是用于类文件的操作
  2:构造context(第八章会详细讲解构造context)
   context最主要的是有__enter__()与__exit__()方法,分别在with语句开始和结束时调用
   抛出的问题都会以traceback参数传递到__exit__()函数中,应该做相应处理。   例子:错误处理context:在打开文件时做备份,若处理完文件没出问题就删除备份,若出了问题就使用备份来恢复原文件
 import os
class Updating:
def __init__( self, filename ):
self.filename= filename
def __enter__( self ): #做文件备份
try:
self.previous= self.filename+" copy"
os.rename( self.filename, self.previous )
except FileNotFoundError:
# Never existed, no previous copy
self.previous= None def __exit__( self, exc_type, exc_value, traceback ): #
if exc_type is not None:
try:
os.rename( self.filename, self.filename+ " error" )
except FileNotFoundError:
pass # Never even got created?
if self.previous:
os.rename( self.previous, self.filename ) #用备份文件恢复原文件 with Updating( "some_file" ):
with open( "some_file", "w" ) as target:
process( target )
												

python面对对象编程----------7:callable(类调用)与context(上下文)的更多相关文章

  1. python面对对象编程------4:类基本的特殊方法__str__,__repr__,__hash__,__new__,__bool__,6大比较方法

    一:string相关:__str__(),__repr__(),__format__() str方法更面向人类阅读,print()使用的就是str repr方法更面对python,目标是希望生成一个放 ...

  2. python面对对象编程----2:__init__

    面对对象编程估计我们最早接触到的就是__init__了,也就是实例的初始化处理过程: 1:来看看最基础的__init__ class Card(object): #抽象类Card,并不用于实例化 de ...

  3. python面对对象编程---------6:抽象基类

    抽象基本类的几大特点: 1:要定义但是并不完整的实现所有方法 2:基本的意思是作为父类 3:父类需要明确表示出那些方法的特征,这样在写子类时更加简单明白 用抽象基本类的地方: 1:用作父类 2:用作检 ...

  4. python面对对象编程中会用到的装饰器

    1.property 用途:用来将对像的某个方法伪装成属性来提高代码的统一性. class Goods: #商品类 discount = 0.8 #商品折扣 def __init__(self,nam ...

  5. python面对对象编程-------5:获取属性的四种办法:@property, __setattr__(__getattr__) ,descriptor

    一:最基本的属性操作 class Generic: pass g= Generic() >>> g.attribute= "value" #创建属性并赋值 > ...

  6. python面对对象编程----1:BlackJack(21点)

    昨天读完了<Mastering Object-oriented Python>的第一部分,做一些总结. 首先,第一部分总过八章,名字叫Pythonic Classes via Specia ...

  7. 跟着百度学PHP[4]OOP面对对象编程-12-抽象类

    什么是抽象方法?我们在类里面定义的没有方法体的方法就是抽象方法.所谓的没有方法体指的是,在方法声明的时候没有大括号以及其中的内容,而是直接在声明时在方法名后加上分号结束,另外在声明抽象方法时还要加一个 ...

  8. python面对对象编程------3:写集合类的三种方法

    写一个集合类的三种方法:wrap,extend,invent 一:包装一个集合类 class Deck: def __init__( self ): self._cards = [card6(r+1, ...

  9. Python学习6——再谈抽象(面对对象编程)

    1.对象魔法 在面对对象编程中,术语对象大致意味着一系列数据(属性)以及一套访问和操作这些数据的方法. 使用对象而非全局变量以及函数的原因有多个,而最重要的好处不过以下几点: 多态:可对不同类型的对象 ...

随机推荐

  1. hdfs 常用命令

    (2)bin/hdfs dfs -mkdir -p /home/雨渐渐 (3)scp /media/root/DCE28B65E28B432E/download/第2周/ChinaHadoop第二讲\ ...

  2. tomcat源码阅读

    1      工具准备 需要SVN.Maven.JDK.Eclipse.Eclipse M2插件 2      下载源码及发布包 源码在这里:http://svn.apache.org/repos/a ...

  3. BZOJ 1507 Editor

    Description Input 输入文件editor.in的第一行是指令条数t,以下是需要执行的t个操作.其中: 为了使输入文件便于阅读,Insert操作的字符串中可能会插入一些回车符,请忽略掉它 ...

  4. SVN简明使用方法 .

    SVN简明使用方法 TortoiseSVN 是 Subversion 版本控制系统的一个免费开源客户端,可以超越时间的管理文件和目录.文件保存在中央版本库,除了能记住文件和目录的每次修改以外,版本库非 ...

  5. 为Ubuntu配置ssh服务 方便远程登陆

    Ubuntu系统必须开启ssh服务后,XP或者其他的主机才可以远程登陆到Ubuntu系统. 1,安装软件包,执行sudo apt-get install openssh-server Ubuntu缺省 ...

  6. ios入门之c语言篇——基本函数——4——数值交换函数

    一个常用函数,被整理出来,免得每次 都要写 参数返回值解析: 参数: *a:int*,需要交换值的第一个变量: *b:int*,需要交换值的第二个变量: 返回值: (无) 函数解析: swap(&am ...

  7. HTML入门教程(全套)

    http://www.rm5u.com/html_html.html http://learn.shayhowe.com/  moe.mwulu.com  http://www.w3school.co ...

  8. 静态与动态IP设置

    静态IP设置 netsh interface ipv4 set address name="本地连接" source=static addr=192.168.0.212 (这个地方 ...

  9. Mac开发者必备实用工具推荐

    最近一个师兄给我推荐了一些Mac上的实用工具,用起来非常顺手,能提高不少开发效率.于是就想着把自己之前用过的其他工具也整理一下,一块推荐给大家,希望能对大家有帮助. Alfred 目前Mac下最好用的 ...

  10. Surprising Strings(map类)

    http://poj.org/problem?id=3096 题意容易理解,开始直接暴力,还是用map写下吧,熟练一下: #include<stdio.h> #include<str ...