Examples of special methods for Python, and analysis of python instances

Source: Internet
Author: User

Examples of special methods for Python, and analysis of python instances

This example describes the special methods of the Python class. 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
Copy codeThe 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
Copy codeThe 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.
Copy codeThe 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:
Copy codeThe Code is as follows: print objectOfClass
Python will call the _ str _ method of the object and output 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, 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:
Copy codeThe Code is as follows: print phone
The following statement is executed:
Copy codeThe 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
Copy codeThe 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.
Copy codeThe 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.
Copy codeThe 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.
Copy codeThe 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.