| 
                         这是迭代器方法!列表、字典、元组之所以可以进行for循环,是因为其内部定义了  iter()这个方法。如果用户想让自定义的类的对象可以被迭代,那么就需要在类中定义这个方法,并且让该方法的返回值是一个可迭代的对象。当在代码中利用for循环遍历对象时,就会调用类的这个iter()方法。 
普通的类: 
- class Foo: 
 -     pass 
 - obj = Foo() 
 - for i in obj: 
 -     print(i) 
 - # 报错:TypeError: 'Foo' object is not iterable<br># 原因是Foo对象不可迭代 
 - 添加一个__iter__(),但什么都不返回: 
 - class Foo: 
 -     def __iter__(self): 
 -         pass 
 - obj = Foo() 
 - for i in obj: 
 -     print(i) 
 - # 报错:TypeError: iter() returned non-iterator of type 'NoneType' 
 - #原因是 __iter__方法没有返回一个可迭代的对象 
 
  
返回一个个迭代对象: 
- class Foo: 
 -     def __init__(self, sq): 
 -         self.sq = sq 
 -     def __iter__(self): 
 -         return iter(self.sq) 
 - obj = Foo([11,22,33,44]) 
 - for i in obj: 
 -     print(i) 
 
  
最好的方法是使用生成器: 
- class Foo: 
 -     def __init__(self): 
 -         pass 
 -     def __iter__(self): 
 -         yield 1 
 -         yield 2 
 -         yield 3 
 - obj = Foo() 
 - for i in obj: 
 -     print(i) 
 
  
10、len() 
在Python中,如果你调用内置的len()函数试图获取一个对象的长度,在后台,其实是去调用该对象的len()方法,所以,下面的代码是等价的: 
- len('ABC') 
 - 3 
 - 'ABC'.__len__() 
 - 3 
 
  
Python的list、dict、str等内置数据类型都实现了该方法,但是你自定义的类要实现len方法需要好好设计。 
11. repr() 
这个方法的作用和str()很像,两者的区别是str()返回用户看到的字符串,而repr()返回程序开发者看到的字符串,也就是说,repr()是为调试服务的。通常两者代码一样。 
- class Foo: 
 -     def __init__(self, name): 
 -         self.name = name 
 -     def __str__(self): 
 -         return "this is %s" % self.name 
 -     __repr__ = __str__ 
 
  
12. add__: 加运算 _sub_: 减运算 _mul_: 乘运算 _div_: 除运算 _mod_: 求余运算 __pow: 幂运算 
这些都是算术运算方法,需要你自己为类设计具体运算代码。有些Python内置数据类型,比如int就带有这些方法。Python支持运算符的重载,也就是重写。 
- class Vector: 
 -    def __init__(self, a, b): 
 -       self.a = a 
 -       self.b = b 
 -    def __str__(self): 
 -       return 'Vector (%d, %d)' % (self.a, self.b) 
 -    def __add__(self,other): 
 -       return Vector(self.a + other.a, self.b + other.b) 
 - v1 = Vector(2,10) 
 - v2 = Vector(5,-2) 
 - print (v1 + v2) 
 
                          (编辑:滁州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |