Special methods for Python classes
Python classes can define specialized methods that are called by Python for you in special cases or when using special syntax, rather than directly in code (as in normal methods).
.1 __init__
Similar to constructors
#!/usr/local/bin/python
Class Study:
def __init__ (Self,name=none):
Self.name = Name
Def say (self):
Print Self.name
Study = study ("Badboy")
Study.say ()
.2 __del__
Similar to destructors
#!/usr/local/bin/python
Class Study:
def __init__ (Self,name=none):
Self.name = Name
def __del__ (self):
Print "iamaway,baby!"
Def say (self):
Print Self.name
Study = study ("Zhuzhengjun")
Study.say ()
.3__repr__
When using repr (obj), the __repr__ function is called automatically, which returns an object string expression,
Used to reconstruct an object if eval (repr (obj)) Gets a copy of an object.
#!/usr/local/bin/python
Class Study:
def __init__ (Self,name=none):
Self.name = Name
def __del__ (self):
Print "iamaway,baby!"
Def say (self):
Print Self.name
def __repr__ (self):
Return "Study (' Jacky ')"
Study = study ("Zhuzhengjun")
Study.say ()
Print type (repr (Study ("Zhuzhengjun")) # str
Print type (eval (repr (Study ("Zhuzhengjun"))) # instance
Study = eval (repr (Study ("Zhuzhengjun"))
Study.say ()
.4__str__
Python can output built-in data types with print statements. Sometimes the programmer wants to define a class that requires its objects to be output with print statements. The Python class defines a special method, __str__, that provides an informal string representation of the object of the class. If the client program for the class contains the following statement:
Print Objectofclass
Then python invokes the object's __str__ method and outputs the string returned by that method.
#!/usr/local/bin/python
Class PhoneNumber:
def __init__ (Self,number):
Self.areacode=number[1:4]
Self.exchange=number[6:9]
SELF.LINE=NUMBER[10:14]
def __str__ (self):
Return "(%s)%s-%s"% (self.areacode,self.exchange,self.line)
def test ():
Newnumber=raw_input ("Enter phone number in the" form.) (123) 456-7890: \ n ")
Phone=phonenumber (Newnumber)
Print "The phone number is:"
Print phone
if__name__== "__main__":
Test ()
Method __init__ receives a string that is shaped like "(XXX) xxx-xxxx". Each x in the string is a single digit of the phone number. method to decompose a string and store the different parts of the phone number as attributes.
Method __str__ is a special method that constructs and returns a string representation of an object of the PhoneNumber class. Once the parser encounters the following statement:
Print phone
The following statement is executed:
Print phone.__str__ ()
Python also calls the __str__ method if the PhoneNumber object is passed to the built-in function str (such as STR), or if the PhoneNumber object uses the string formatting operator% (for example, "%s"%phone).
.5__CMP __
Comparison operator, 0: equals 1: Greater than-1: less than
Class Study:
def __cmp__ (self, Other):
If other > 0:
Return 1
Elif Other < 0:
Return-1
Else
return 0
Study = study ()
If study > -10:print ' Ok1 '
If study < -10:print ' Ok2 '
If study = = 0:print ' Ok3 '
Printed: Ok2 OK3
Description: When comparing classes, Python automatically calls the __cmp__ method, such as -10 < 0 to return 1, that is, study should be small and-10, to estimate the printing ok2
.6__getitem__
The __getitem__ method is simple. Like the normal method Clear,keys and values, it simply redirects to the dictionary and returns the value of the dictionary.
Class Zoo:
def __getitem__ (self, key):
If key = = ' dog ': Return ' dog '
elif key = = ' pig ': return ' pig '
elif key = = ' Wolf ': Return ' wolf '
Else:return ' Unknown '
Zoo = Zoo ()
Print zoo[' dog ']
Print zoo[' pig ']
Print zoo[' wolf '
Print Dog pig Wolf
.7__setitem__
__setitem__ simply redirects to the real dictionary self.data, allowing it to work.
Class Zoo:
def __setitem__ (self, Key, value):
print ' key=%s,value=%s '% (key, value)
Zoo = Zoo ()
Zoo[' a '] = ' a '
Zoo[' b '] = ' B '
Zoo[' c '] = ' C '
Print:
Key=a,value=a
Key=b,value=b
Key=c,value=c
.8 __delitem__
__delitem__ is called when you call Del Instance[key], and you may remember it as a way to remove a single element from the dictionary. When you use Del in a class instance, Python calls the __delitem__ private method for you.
Class A:
def __delitem__ (self, key):
print ' Delete item:%s '%key
A = A ()
Del a[' key ']
Operator overloading is the same as C + +, and Python can overload operators. The methods that can be overloaded are shown in the following table.
| Method |
Overloads |
| Call for
| Init |
constructor function |
X=class () |
| Del |
Destructors |
Object Destruction |
| Repr |
Print Conversion |
Print X,repr (X) |
| Str |
Print Conversion |
Print X,str (X) |
| Pager |
Calling functions |
X () |
| GetAttr |
Limit |
X.undefine |
| SetAttr |
Take value |
X.any=value |
| GetItem |
Index |
X[key],for If |
| SetItem |
Index |
X[key]=value |
| Len |
Length |
Len (X) |
| Iter |
Iteration |
For in |
| Add |
+ |
X+y,x+=y |
| Sub |
- |
X-y,x-=y |
| Mul |
|
Xy |
| Radd |
Right Plus + |
+x |
| Iadd |
+= |
X+=y |
| Or |
| |
X| Y,x|=y |
| Cmp |
Compare = = |
X==y,x |
| Lt |
Less than < |
X |
| eq |
equals = |
X=y |
Class number (object):d EF __init__ (Self, value): Self.value = value# heavy Load def __add__ (self, Other): Return number (Self.value + other.value) # print overload def __str__ (self): Return ' The value is%d. '% self.value# compare overload def __cmp__ (Self, Other): Return CMP (self . Value, Other.value) >>> x = number (1) >>> y = number (2) >>> print X + ythe value is 3.>>> ; x > Yfalse>>> x < ytrue
Reference documents:
http://5ydycm.blog.51cto.com/115934/157548
http://wuyuans.com/2013/05/python-class/
Overloads of methods such as Python