1.item系列方法

# class Foo:
# def __getitem__(self, item):
# print('getitem',item)
# return self.__dict__[item]
#
# def __setitem__(self, key, value):
# print('setitem')
# self.__dict__[key]=value
#
# def __delitem__(self, key):
# print('delitem')
# self.__dict__.pop(key)
#
class Foo:
def __getitem__(self, item):
print('getitem',item)
return self.__dict__[item] def __setitem__(self, key, value):
print('setitem')
self.__dict__[key] = value def __delitem__(self, key):
print('delitem')
self.__dict__.pop(key) f1 = Foo()
print(f1.__dict__)
f1.name = 'egon'
# f1['name'] = 'egon'
f1['age'] = 18
# print(f1.__dict__) # del f1.name
# print(f1.age) # del f1['name']
# print(f1.__dict__)
print(f1['age'])
raise StopAsyncIteration
# f1=Foo()
# print(f1.__dict__)
# # f1.name='egon' #---->setattr-------->f1.__dict__['name']='egon'
# f1['name']='egon'#--->setitem--------->f1.__dict__['name']='egon'
# f1['age']=18
#
# print('===>',f1.__dict__)
#
# # del f1.name
# # print(f1.__dict__)
# #
# # print(f1.age)
# del f1['name']
# print(f1.__dict__)
#
# print(f1['age'])
# raise S

2.slots属性

class Foo:
__slots__ = ['name','age'] f1 = Foo()
f1.name = 'egon'
print(f1.name) # class Foo:
# __slots__=['name','age'] #{'name':None,'age':None}
# __slots__='name' #{'name':None,'age':None} # f1=Foo()
# f1.name='egon'
# print(f1.name) # f1.age=18 #--->setattr----->f1.__dict__['age']=18 f1.age = 18
# print(f1.__dict__)
print(Foo.__slots__)
print(f1.__slots__) f1.name = 'egon'
f1.age = 17
print(f1.name)
print(f1.age)
# print(f1.__dict__)
# print(Foo.__slots__)
# print(f1.__slots__)
# f1.name='egon'
# f1.age=17
# print(f1.name)
# print(f1.age)
# f1.gender='male' # f1.gender = 'male' f2 = Foo()
print(f2.__slots__)
f2.name = 'alex'
f2.age = 18
print(f2.name)
print(f2.age) # f2=Foo()
# print(f2.__slots__)
# f2.name='alex'
# f2.age=18
# print(f2.name)
# print(f2.age)

3.内置方法

class Foo:
x = 1
def __init__(self,y):
self.y = y def __getattr__(self, item):
print('------> from getattr:你找的属性不存在') def __setattr__(self, key, value):
print('-----> from setattr')
self.__dict__[key] = value def __delattr__(self, item):
print('-----> from delattr')
self.__dict__.pop(item) f1 = Foo(10) # class Foo:
# x=1
# def __init__(self,y):
# self.y=y
#
# def __getattr__(self, item):
# print('----> from getattr:你找的属性不存在')
#
#
# def __setattr__(self, key, value):
# print('----> from setattr')
# # self.key=value #这就无限递归了,你好好想想
# # self.__dict__[key]=value #应该使用它
#
# def __delattr__(self, item):
# print('----> from delattr')
# # del self.item #无限递归了
# self.__dict__.pop(item)
#
#
# f1=Foo(10)
# f1.x

4.描述符

# class Foo:
# def __get__(self, instance, owner):
# print('===>get方法')
# def __set__(self, instance, value):
# print('===>set方法',instance,value)
# instance.__dict__['x']=value #b1.__dict__
# def __delete__(self, instance):
# print('===>delete方法') class Foo:
def __get__(self, instance, owner):
print('===>get方法') def __set__(self, instance, value):
print('===>set方法',instance,value)
instance.__dict__['x'] = value
def __delete__(self, instance):
print('===>delete方法')
class Bar:
x = Foo()
def __init__(self,n):
self.x = n
b1 = Bar(10)
print(b1.__dict__)
b1.x = 11111111111
print(b1.__dict__) # class Bar:
# x=Foo() #在何地?
# def __init__(self,n):
# self.x=n #b1.x=10
# b1=Bar(10)
# print(b1.__dict__)
# b1.x=11111111111111111
# print(b1.__dict__)
#
b1.y = 111111111111111111111111
print(b1.__dict__)
print(Bar.__dict__) # b1.y=11111111111111111111111111111111111111
# print(b1.__dict__)
# print(Bar.__dict__) b1 = Bar()
b1.x = 1
# del b1.x
print(b1.x)
#在何时?
# b1=Bar()
# b1.x
#
# b1.x=1
#
# del b1.x # print(b1.x)
#
# b1.x=1
# print(b1.__dict__)
#
# del b1.x

5.描述符优先级

# class Foo:
# def __get__(self, instance, owner):
# print('===>get方法')
#
# def __set__(self, instance, value):
# print('===>set方法',instance,value)
#
# def __delete__(self, instance):
# print('===>delete方法') # class Foo:
# def __get__(self, instance, owner):
# print('===>get方法')
# def __set__(self, instance, value):
# print('===>set方法',instance,value)
# # instance.__dict__['x']=value #b1.__dict__
# def __delete__(self, instance):
# print('===>delete方法')
#
# # class Bar:
# x=Foo() #在何地? # print(Bar.x) # Bar.x=1
# print(Bar.__dict__)
# print(Bar.x) # print(Bar.__dict__)
# b1=Bar()
# b1.x #get
# b1.x=1 # set
# del b1.x # delete # b1=Bar()
# Bar.x=111111111111111111111111111111111111111
# b1.x
#
# del Bar.x
# b1.x class Foo:
def __get__(self, instance, owner):
print('===>get方法') def __delete__(self, instance):
print('===>delete方法') class Bar:
x = Foo()
def __getattr__(self, item):
print('-------->') b1 = Bar()
# b1.x = 1
print(b1.__dict__)
# class Foo:
# def __get__(self, instance, owner):
# print('===>get方法')
#
#
# # def __delete__(self, instance):
# # print('===>delete方法')
#
#
# class Bar:
# x=Foo() #在何地?
# def __getattr__(self, item):
# print('----->')
#
# b1=Bar()
# b1.x=1
# print(b1.__dict__)
# b1.xxxxxxxxxxxxxxxxxxxxxxx

6.改变对象的字符串显示

# l=list('hello')
#
# print(l)
# file=open('test.txt','w')
# print(file) # class Foo:
# def __init__(self,name,age):
# self.name=name
# self.age=age
# def __str__(self):
# return '名字是%s 年龄是%s' %(self.name,self.age)
#
# f1=Foo('egon',18)
# print(f1) #str(f1)--->f1.__str__()
#
# x=str(f1)
# print(x)
#
# y=f1.__str__()
# print(y) class Foo:
def __init__(self,name,age):
self.name = name
self.age = age def __str__(self):
return '折是str' def __repr__(self):
return '名字是%s 年龄是%s' %(self.name,self.age) f1 = Foo('as',12)
f1.__repr__() # class Foo:
# def __init__(self,name,age):
# self.name=name
# self.age=age
# # def __str__(self):
# # return '折是str'
# def __repr__(self):
# return '名字是%s 年龄是%s' %(self.name,self.age)
#
# f1=Foo('egon',19)
# #repr(f1)---->f1.__repr__()
# print(f1) #str(f1)---》f1.__str__()------>f1.__repr__()

7.析构方法

# class Foo:
# def __init__(self,name):
# self.name=name
# def __del__(self):
# print('我执行啦')
#
# f1=Foo('alex')
#
# # del f1 #删除实例会触发__del__
# del f1.name #删除实例的属性不会触发__del__
# print('--------------------->')
#
# #程序运行完毕会自动回收内存,触发__del__ class Foo:
def __init__(self,name):
self.name = name def __del__(self):
print('我执行啦') f1 = Foo('andy')
# del f1.name

8.自定义格式化方法format

# x='{0}{0}{0}'.format('dog')
#
# print(x) # class Date:
# def __init__(self,year,mon,day):
# self.year=year
# self.mon=mon
# self.day=day
# d1=Date(2016,12,26)
#
# x='{0.year}{0.mon}{0.day}'.format(d1)
# y='{0.year}:{0.mon}:{0.day}'.format(d1)
# z='{0.mon}-{0.day}-{0.year}'.format(d1)
# print(x)
# print(y)
# print(z) # x='{0.year}{0.mon}{0.day}'.format(d1)
# y='{0.year}:{0.mon}:{0.day}'
# z='{0.mon}-{0.day}-{0.year}' # format_dic={
# 'ymd':'{0.year}{0.mon}{0.day}',
# 'm-d-y':'{0.mon}-{0.day}-{0.year}',
# 'y:m:d':'{0.year}:{0.mon}:{0.day}'
# }
format_dic = {
'ymd':'{0.year}{0.mon}{0.day}',
'm-d-y':'{0.mon}-{0.day}-{0.year}',
'y:m:d':'{0.year}:{0.mon}:{0.day}'
}
class Date:
def __init__(self,year,mon,day):
self.year = year
self.mon = mon
self.day = day def __format__(self, format_spec):
print('我执行啦')
print('--->',format_spec)
if not format_spec or format_spec not in format_dic:
format_spec = 'ymd'
fm = format_dic[format_spec]
return fm.format(self) d1 = Date(2016,12,13)
print(format(d1,'ymd'))
print(format(d1,'y:m:d'))
print(format(d1,'m-d-y'))
print(format(d1,'m-d:y'))
# class Date:
# def __init__(self,year,mon,day):
# self.year=year
# self.mon=mon
# self.day=day
# def __format__(self, format_spec):
# print('我执行啦')
# print('--->',format_spec)
# if not format_spec or format_spec not in format_dic:
# format_spec='ymd'
# fm=format_dic[format_spec]
# return fm.format(self)
# d1=Date(2016,12,26)
# # format(d1) #d1.__format__()
# # print(format(d1))
# print(format(d1,'ymd'))
# print(format(d1,'y:m:d'))
# print(format(d1,'m-d-y'))
# print(format(d1,'m-d:y'))
# print('===========>',format(d1,'asdfasdfsadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasd')) print('=============>',format(d1,'assddd'))

9.迭代器协议

# class Foo:
# def __init__(self,n):
# self.n=n
# def __iter__(self):
# return self
#
# def __next__(self):
# if self.n == 13:
# raise StopIteration('终止了')
# self.n+=1
# return self.n class Foo:
def __init__(self,n):
self.n = n
def __iter__(self):
return self def __next__(self):
if self.n == 13:
raise StopIteration('终止了') self.n+=1
return self.n
f1 = Foo(10)
print(f1.__next__())
print(f1.__next__()) # l=list('hello')
# for i in l:
# print(i)
# f1=Foo(10)
# # print(f1.__next__())
# # print(f1.__next__())
# # print(f1.__next__())
# # print(f1.__next__())
#
# for i in f1: # obj=iter(f1)------------>f1.__iter__()
# print(i) #obj.__next_() for i in f1:
print(i)

10.迭代器协议实现斐波那契数列

# class Fib:
# def __init__(self):
# self._a=1
# self._b=1
#
# def __iter__(self):
# return self
# def __next__(self):
# if self._a > 100:
# raise StopIteration('终止了')
# self._a,self._b=self._b,self._a + self._b
# return self._a
class Fib:
def __init__(self):
self._a = 1
self._b = 1 def __iter__(self):
return self def __next__(self):
if self._a > 100:
raise StopIteration('终止了') self._a,self._b=self._b,self._a+self._b
return self._a f1 = Fib() print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
# f1=Fib()
# print(next(f1))
# print(next(f1))
# print(next(f1))
# print(next(f1))
# print(next(f1))
# print('==================================')
# for i in f1:
# print(i)

day27-python之迭代器协议的更多相关文章

  1. python学习------迭代器协议和生成器

    一.递归和迭代 递归:自己调用自己 举例解释:问路   A问B康明网络科技怎么走,B说我不是很清楚,我帮你问问C,C说我也不知道.我问问D,D说 就在兴隆.之后D返回结果给C,C返回结果给B,B返回结 ...

  2. 第十六篇 Python之迭代器与生成器

    一.迭代器 一. 递归和迭代 生活实例说明什么是递归和迭代 A想去腾达大厦,问B怎么走路,B 说我不知道,我给你问问C,C也不知道,C又去问D,D知道,把路告诉了C,C又告诉B,B最后告诉A, 这就是 ...

  3. python 迭代器协议和生成器

    一.什么是迭代器协议 1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个stoplteration异常,以终止迭代(只能往后走,不能往前退) 2.可迭代 ...

  4. Python之路(第十篇)迭代器协议、for循环机制、三元运算、列表解析式、生成器

    一.迭代器协议 a迭代的含义 迭代器即迭代的工具,那什么是迭代呢? #迭代是一个重复的过程,每次重复即一次迭代,并且每次迭代的结果都是下一次迭代的初始值 b为何要有迭代器? 对于序列类型:字符串.列表 ...

  5. python基础之迭代器协议和生成器

    迭代器和生成器补充:http://www.cnblogs.com/luchuangao/p/6847081.html 一 递归和迭代 略 二 什么是迭代器协议 1.迭代器协议是指:对象必须提供一个ne ...

  6. Python之路迭代器协议、for循环机制、三元运算、列表解析式、生成器

    Python之路迭代器协议.for循环机制.三元运算.列表解析式.生成器 一.迭代器协议 a迭代的含义 迭代器即迭代的工具,那什么是迭代呢? #迭代是一个重复的过程,每次重复即一次迭代,并且每次迭代的 ...

  7. Python之面向对象slots与迭代器协议

    Python之面向对象slots与迭代器协议 slots: # class People: # x=1 # def __init__(self,name): # self.name=name # de ...

  8. python基础之迭代器协议和生成器(一)

    一 递归和迭代 二 什么是迭代器协议 1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代 (只能往后走不能往前 ...

  9. python面向对象的多态-类相关内置函数-类内置魔法函数-迭代器协议-上下文管理-04

    多态 一种事物具备不同的形态 例如:水 --> 固态.液态.气态 多态:# 多个不同对象可以相应同一个对象,产生不同的结果 首先强调,多态不是一种特殊的语法,而是一种状态,特性(多个不同对象可以 ...

  10. (转)python基础之迭代器协议和生成器(一)

    一 递归和迭代 二 什么是迭代器协议 1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代 (只能往后走不能往前 ...

随机推荐

  1. 006 vue监控

    一:监视 1.使用keyup <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...

  2. Eclipse创建Maven父子项目

    Eclipse创建Maven父子项目 - 木头若愚 - CSDN博客https://blog.csdn.net/jay_1989/article/details/53906995 创建maven项目是 ...

  3. NTP时钟同步配置

    NTP在Linux下有两种时钟同步方式: 直接同步(也称跳跃同步)和平滑同步(也称微调同步). 直接同步 使用ntpdate命令进行同步,直接进行时间变更. 如果服务器上存在一个12点运行的任务,当前 ...

  4. Mac 上ssh远程连接Linux服务器提示Host key verification failed.

    当我们对重装远程服务器的时候会出现Host key verification failed问题 解决办法: rm -rf ~/.ssh/known_hosts 重新ssh连接,OK!

  5. Sword libcurl库CURLE_COULDNT_CONNECT错误

    CURL: CURLE_COULDNT_CONNECT问题分析 测试环境描述在使用libcurl写http客户端进行压力测试的时候会遇到curl_easy_perform()返回CURLE_COULD ...

  6. react 模板备份

    /** * Created by hldev on 17-6-14. * 上市公司详情展示界面 */ import React, {Component} from "react"; ...

  7. [LeetCode] 678. Valid Parenthesis String 验证括号字符串

    Given a string containing only three types of characters: '(', ')' and '*', write a function to chec ...

  8. 【Python学习之十】操作数据库

    环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 python3.6 操作mysql数据库 1.安装pymysql模块p ...

  9. Mybatis获取数据库自增主键

    一般我们都为将表中主键列设置为自增,当我们执行插入语句时,比如这样 //测试添加 Employee employee = new Employee(null, "jerry4",n ...

  10. Mysql 学习整理

    1 创建数据库 1.1数据库基本结构 数据库:数据库是表的集合,带有相关的数据. 表:一个表是多个字段的集合. 字段:一个字段是一列数据,由字段名和记录组成 1.2创建数据库 create datab ...