The examples in this article describe the specialized methods for Python classes. Share to everyone for your reference. The specific analysis is as follows:
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
Copy the Code code as follows:
#!/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
Copy the Code code as follows:
#!/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_r (repr (obj)) Gets a copy of the object.
Copy the Code code as follows:
#!/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_r (repr (Study ("Zhuzhengjun"))) # instance
Study = Eval_r (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:
Copy the Code code as follows:
Print Objectofclass
Then python invokes the object's __str__ method and outputs the string returned by that method.
Copy CodeThe code is as follows:
#!/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:
Copy the Code code as follows:
Print phone
The following statement is executed:
Copy CodeThe code is as follows:
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
Copy the Code code as follows:
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.
Copy the Code code as follows:
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.
Copy the Code code as follows:
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.
Copy the Code code as follows:
Class A:
def __delitem__ (self, key):
print ' Delete item:%s '%key
A = A ()
Del a[' key ']
Hopefully this article will help you with Python programming.