#!/usr/bin/env python #-*-coding:utf-8-*-' Custom class ' __author__ = ' Hui.qian ' class Student (object): Def __init__ (sel F,name): Self.name = name s = Student (' Hui.qian ') s print S #添加__str__方法, equivalent to the ToString () class Student in Java (object ): Def __init__ (self,name): self.name = name def __str__ (self): Return ' Student object (name:%s) '% Self.name S1 = Student (' Zuomu.qian ') print ' S1: ' S1 print ' Print S1: ' Print S1 #添加__repr__, knocking directly at the command line S1 displays the same class as print S1 Student (object): Def __init__ (self,name): self.name = name def __str__ (self): return ' Student obje CT (name:%s) '%self.name __repr__ = __str__ s2 = Student (' Zuomu.qian ') s2 print s2 #__iter__迭代方法, objects added to this method can be used for ...
In Iteration class Calculate_1 (object): Def __init__ (self): self.a=0 def __iter__ (self): return self; Def next (self): self.a +=1 if Self.a>100:raise stopiteration () return SELF.A #fo R N in Calculate_1 (): # priNT N #__getitem__可让上面的类和list一样, the subscript method can be used to remove class calculate_2 (object): Def __getitem__ (self,n): a = 0 f or x in range (n+1): a = x+1 return a f = calculate_2 () print f[1] Print f[3] Print f[0] class Calcula Te_3 (object): Def __getitem__ (self,n): If Isinstance (n,int): a = 0 for x in range (n+1) : a = x+1 elif isinstance (n,slice): L = [] A = n.start B = n.s Top to X in range (b+1): if (x>=a+1): L.append (x) return L F
1 = calculate_3 () print F1[0:5] #__setitem__对应于dict #__delitem__删除元素