This article mainly introduces the special methods of the Python class, and analyzes the application skills of specialized methods such as _ init _, _ del _, and _ repr, for more information about how to use Python, see the following example. Share it with you for your reference. The specific analysis is as follows:
A Python class can define a special method. a special method is called by Python for you in special circumstances or when special syntax is used, instead of calling it directly in the code (like a common method ).
1. _ init __
Similar to Constructor
The code is 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 Destructor
The code is 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 repr (obj) is used, the _ repr _ function is automatically called, which returns the Object String expression,
Used to recreate an object. if eval_r (repr (obj) is used, a copy of the object will be obtained.
The code is 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 use the print statement to output built-in data types. Sometimes, programmers want to define a class and require its objects to be output using print statements. A Python class can define special method _ str __, which provides an informal string representation for class objects. If the client program of the class contains the following statements:
The code is as follows:
Print objectOfClass
Python will call the _ str _ method of the object and output the string returned by that method.
The 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, such as "(xxx) xxx-xxxx. Each x in the string is the single digit of the phone number. Method to break down the string and store different parts of the phone number as attributes.
Method _ str _ is a special method that constructs and returns a string representation of an object in the PhoneNumber class. The parser encounters the following statement:
The code is as follows:
Print phone
The following statement is executed:
The code is as follows:
Print phone. _ str __()
If the program passes the PhoneNumber object to the built-in function str (such as str (phone), or uses the string formatting operator % (such as "% s" % phone) for the PhoneNumber object ), python also calls the _ str _ method.
5. _ cmp __
Comparison operator, 0: equal to 1: greater than-1: less
The code is 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'
Print: ok2 ok3
Note: When comparing classes, python automatically calls the _ cmp _ method, for example,-10 <0 returns-1, that is, study should be smaller than-10, and ok2 is estimated to be printed.
6. _ getitem __
The _ getitem _ Special method is simple. Like normal methods clear, keys, and values, it only redirects to the dictionary and returns the dictionary value.
The code is 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 to allow it to work.
The code is 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 =
Key = B, value = B
Key = c, value = c
8. _ delitem __
_ Delitem _ is called when del instance [key] is called. you may remember it as a method to delete a single element from the dictionary. When you use del in a class instance, Python calls the _ delitem _ special method for you.
The code is as follows:
Class:
Def _ delitem _ (self, key ):
Print 'delete item: % s' % key
A = ()
Del a ['key']
I hope this article will help you with Python programming.