Python-object-oriented (3)-Special Class Member, python-object-oriented

Source: Internet
Author: User

Python-object-oriented (3)-Special Class Member, python-object-oriented
Special member of the class

 

1. _ doc __ Class description
Class Foo: "Description class information, which is the magic of watching movies" def func (self): passprint Foo. _ doc __================== description class information, this is the magic for watching movies

 

2. _ module _ and _ class __ _ Module _ indicates the module in which the object to be operated is located. _ Class _ indicates the class of the object for the current operation.

 

3._ Init __
Constructor. It is automatically triggered when an object is created through a class.
Class Foo: def _ init _ (self, name): self. name = name self. age = 18obj = Foo ('wupeiqi ') # The _ init _ method in the Automatic Execution class

  

  4. _ del __

The Destructor is automatically triggered when an object is released in the memory.

Note: This method is generally not needed to be defined. Because Python is a high-level language, programmers do not need to worry about memory allocation and release when using it, because this job is to be executed by the Python interpreter, the Destructor is automatically triggered by the interpreter during garbage collection.

class Foo:    def__del__(self):        pass

 

5. _ call __ The object is enclosed in parentheses to trigger execution.   Note: The execution of the constructor method is triggered by the creation object, that is, the object = Class Name (). The execution of the _ call _ method is triggered by the brackets behind the object, that is, object () or class ()()
Class Foo: def _ init _ (self): passdef _ call _ (self, * args, ** kwargs ): print '_ call _' obj = Foo () # Run _ init _ obj () # Run _ call __

 

6. _ dict __  All members in a class or object

In the above article, we know that the common fields of the class belong to the object, and the static fields and methods in the class belong to the class, that is:

 

 

Class Province: country = 'China' def _ init _ (self, name, count): self. name = name self. count = count def func (self, * args, ** kwargs): print 'func' # obtain the class members, that is, static fields and methods...
Print Province. _ dict __# output: {'country': 'China', '_ module _': '_ main _', 'func ': <function func at 0x10be30f50>, '_ init _': <function _ init _ at 0x10be30ed8>, '_ doc __': none} # obtain the member of object obj1
Obj1 = Province ('hebei', 10000) print obj1. _ dict __# output: {'Count': 10000, 'name': 'hebei '}

 

7. _ str __ If the _ str _ method is defined in a class, the return value of this method is output by default when an object is printed.
Class Foo: def _ str _ (self): return 'wupeiqi 'obj = Foo () print obj # output: wupeiqi

 

8, _ Getitem __ , _ Setitem __ , _ Delitem __  Used for index operations, such as dictionaries. The preceding parameters indicate obtaining, setting, and deleting data respectively.

 

#! /Usr/bin/env python #-*-coding: UTF-8-*-class Foo (object): def _ getitem _ (self, key ): print '_ getitem _', key def _ setitem _ (self, key, value): print '_ setitem _', key, value def _ delitem _ (self, key): print '_ delitem _', key obj = Foo () result = obj ['k1 '] # automatically triggered execution _ getitem _ obj ['k2'] = 'wupeiqi' # automatically triggered execution _ setitem _ del obj [' k1 '] # automatically triggered execute _ delitem __

 

9. _ getslice _, _ setslice _, and _ delslice __ The three methods are used for partitioning, for example, list Slice: Slice Cutting
#! /Usr/bin/env python #-*-coding: UTF-8-*-class Foo (object): def _ getslice _ (self, I, j ): print '_ getslice _', I, j def _ setslice _ (self, I, j, sequence): print '_ setslice _', I, j def _ delslice _ (self, I, j): print '_ delslice _', I, jobj = Foo () obj [-] # automatically triggered execution _ getslice _ obj [] = [, 22, 33,44] # automatically triggered execute _ setslice _ del obj [0: 2] # automatically triggered execute _ delslice __

 

10. _ iter __  For the iterator, The for loop can be performed for lists, dictionaries, and tuples because _ iter _ is defined in the type __
  Step 1:
Class Foo (object): passobj = Foo () for I in obj: print I # error: TypeError: 'foo' object is not iterable iteratable

Step 2:

#! /Usr/bin/env python #-*-coding: UTF-8-*-class Foo (object): def _ iter _ (self): passobj = Foo () for I in obj: print I # error: TypeError: iter () returned non-iterator of type 'nonetype'

Step 3:

#!/usr/bin/env python# -*- coding:utf-8 -*-class Foo(object):    def__init__(self, sq):        self.sq = sq    def__iter__(self):        return iter(self.sq)obj = Foo([11,22,33,44])for i in obj:    print i

The above steps show that the for loop iteration is actually iter ([,]), so the execution process can be changed:

 

#! /Usr/bin/env python #-*-coding: UTF-8-*-obj = iter ([,]) for I in obj: print IInside the For loop syntax#! /Usr/bin/env python #-*-coding: UTF-8-*-obj = iter ([,]) while True: val = obj. next () print val

  

  11. _ new _ and _ metaclass __
Read the following code:
Class Foo (object): def _ init _ (self): pass obj = Foo () # obj is an object instantiated through the Foo class.
  In the above Code, obj is an object instantiated through the Foo class. In fact, not only is obj an object, but the Foo class itself is also an object, because everything in Python is an object.   If everything is an object theory: the obj object is created by executing the Foo class constructor, the Foo class object should also be created by executing the constructor of a class. 
Print type (obj) # output: <class '_ main __. foo '> indicates that the obj object is created by the Foo class print type (Foo) # output: <type 'type'> indicates that the Foo class object is created by the type class.

So,The obj object is an instance of the Foo class.,The Foo class object is an instance of the type class.That is, the Foo class object is created through the type class constructor.

There are two ways to create a class:  A). Common Mode  
class Foo(object):     def func(self):        print 'hello wupeiqi'
  B). Special method (type class constructor)
 
Def func (self): print 'Hello wupeiqi 'Foo = type ('foo', (object,), {'func': func}) # The first parameter of type: class Name # type second parameter: base class of the current class # type third parameter: class member
  = "Class is produced by type class instantiation

 

 

 

 

 

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.