VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Python基础教程 >
  • python基础教程之python基础(27):类成员的修饰符、类的特殊成员(3)

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. class Foo(object):
  5.  
  6. def __getslice__(self, i, j):
  7. print '__getslice__',i,j
  8.  
  9. def __setslice__(self, i, j, sequence):
  10. print '__setslice__',i,j
  11.  
  12. def __delslice__(self, i, j):
  13. print '__delslice__',i,j
  14.  
  15. obj = Foo()
  16.  
  17. obj[-1:1] # 自动触发执行 __getslice__
  18. obj[0:1] = [11,22,33,44] # 自动触发执行 __setslice__
  19. del obj[0:2] # 自动触发执行 __delslice__

2.10 __iter__ 

用于迭代器,之所以列表、字典、元组可以进行for循环,是因为类型内部定义了 __iter__ 

第一步:


  1. class Foo(object):
  2. pass
  3.  
  4. obj = Foo()
  5.  
  6. for i in obj:
  7. print(i)
  8.  
  9. # 报错:TypeError: 'Foo' object is not iterable

第二步:


  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. class Foo(object):
  5.  
  6. def __iter__(self):
  7. pass
  8.  
  9. obj = Foo()
  10.  
  11. for i in obj:
  12. print(i)
  13.  
  14. # 报错:TypeError: iter() returned non-iterator of type 'NoneType'

第三步:


  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. class Foo(object):
  5.  
  6. def __init__(self, sq):
  7. self.sq = sq
  8.  
  9. def __iter__(self):
  10. return iter(self.sq)
  11.  
  12. obj = Foo([11,22,33,44])
  13.  
  14. for i in obj:
  15. print(i)

以上步骤可以看出,for循环迭代的其实是  iter([11,22,33,44]) ,所以执行流程可以变更为:


  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. obj = iter([11,22,33,44])
  5.  
  6. for i in obj:
  7. print(i)

for循环语法内部:


  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. obj = iter([11,22,33,44])
  5.  
  6. while True:
  7. val = obj.next()
  8. print(val)

2.11 __new__ 和 __metaclass__

 阅读以下代码:


  1. class Foo(object):
  2.  
  3. def __init__(self):
  4. pass
  5.  
  6. obj = Foo() # obj是通过Foo类实例化的对象

上述代码中,obj 是通过 Foo 类实例化的对象,其实,不仅 obj 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象

如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。


  1. print type(obj) # 输出:<class '__main__.Foo'> 表示,obj 对象由Foo类创建
  2. print type(Foo) # 输出:<type 'type'> 表示,Foo类对象由 type 类创建

所以,obj对象是Foo类的一个实例Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。

那么,创建类就可以有两种方式:

1.普通方式


  1. class Foo(object):
  2.  
  3. def func(self):
  4. print 'hello xiaohuihui'

2.特殊方式(type类的构造函数)


  1. def func(self):
  2. print 'hello xiaohuihui'
  3.  
  4. Foo = type('Foo',(object,), {'func': func})
  5. #
相关教程