This article shares with you the main is python The special method of the class in the language related usage, hope to be helpful to everybody.
Construct a sequence
1._len_ (self)
2._getitem_ (Self,key)
3._setitem_ (Self,key,value)
4._delitem_ (Self,key)
Program Demo:
myseq.py
Class Myseq:
def __init__ (self):
Self.lseq = ["I", "II", "III", "IV"]
def __len__ (self):
Return Len (SELF.LSEQ)
def __getitem__ (Self,key):
If 0 <= key < 4:
return Self.lseq[key]
if __name__ = = ' __main__ ':
m = Myseq ()
For I in range (4):
Print (M[i])
The running result of the program is:
Construction of ITER
1._iter_ (self)
2._next_ (self)
The program demonstrates the following:
Class Myiter:
def __init__ (self,start,end):
Self.count = Start
Self.end = End
def __iter__ (self):
return self
def __next__ (self):
If Self.count < self.end:
r = Self.count
Self.count + = 1
Return r
Else
Raise Stopiteration
if __name__ = = ' __main__ ':
For I in Myiter (1,10):
Print (i)
The running result of the program is:
Constructing comparable classes
1._it_()
2._le_ ()
3._gt_ ()
4._ge_ ()
5._eq_ ()
6._ne_ ()
The program demonstrates the following:
mycmp.py
Class Myiter:
def __init__ (self,start,end):
Self.count = Start
Self.end = End
def __iter__ (self):
return self
def __next__ (self):
If Self.count < self.end:
r = Self.count
Self.count + = 1
Return r
Else
Raise Stopiteration
if __name__ = = ' __main__ ':
For I in Myiter (1,10):
Print (i)
The running result of the program is:
Constructing an operational class
1._add_ ()
2._sub_ ()
3._mul_ ()
4._div_ ()
The program demonstrates the following:
Class point:
def __init__ (self,x,y):
self.x = X
Self.y = y
def __add__ (Self,oth):
Return point (self.x + oth.x, Self.y + oth.y)
def info (self):
Print (SELF.X,SELF.Y)
if __name__ = = ' __main__ ':
PA = point (from)
PB = Point (3,4)
PC = PA + PB
Pc.info ()
The running result of the program is:
original link:http://www.maiziedu.com/wiki/python/special/
Special methods for classes in Python