Detailed basic knowledge of Python from entry to the master (eight) magic method

Detailed basic knowledge of Python from entry to the master (eight) magic method

Data in this chapter is to introduce the python, the contents of the directory can look at the
other basics Hi, welcome to view my other articles
basics Python Comments from entry to the master (a) Introduction
(b) explain the basics of Python basis from entry to the master
Python fundamentals Detailed Mastering (c) the syntax and function
basics of Python Comments from entry to the master (d) lists, tuples, dictionaries, a set of
Python Fundamentals Detailed (five) module management from entry to the master
Python fundamentals Comments from entry to proficient (six) file operations
basics of Python Comments (seven) classes and objects from entry to the master

What is the magic method

As the name suggests is to operate magic can give you additional class of 'magic' approach, gives us great flexibility when we need to provide some way for us to get your ideas to achieve, it is well-known support for Python language objects, Python magic method makes Python do better in the face of the object

How to use magic method

Magic method is the internal python has been given, and it is surrounded by a double underscore, it will be automatically invoked in some particular time

We can rewrite a certain magic method, good operation we need to define, in this magic method is called automatically when the operation is finished we need

Basis magic method (more commonly)

  1. __ new __ (cls [, ... ])
    The first method is called when the object is instantiated 1.
    2. the parameters passed directly to the processing method init__ __
    3. We generally do not override this method
    4. When a succession immutable and need to be modified when you need to modify his
  2. __ init __ (self [, ... ])
    constructor initializes the class (instance generation can pass parameters) is called when
  3. __ del __ (self)
    destructor method (to be called when all pointers instantiating objects are destroyed) when instantiating the object being destroyed (no label point to the object) is called is not called when using del, which is equivalent to garbage collection
  4. __ call __ (self [, args ...])
    to allow a class instance like a function is called: x (a, b) calling x .__ call __ (a, b )
  5. __ len (self) __
    behavior is defined when len () call
  6. __ repr __ (self)
    Defines the behavior is rewritten is called the repr () Returns a string that may be implemented
    as
 class h :
	 def __repr__(self):
		return xxx
     		则 a = h()
			运行a 
			结果直接输出xxx

  1. __ str __ (self)
    is defined as the behavior when calling str (), we can rewrite this implementation returns a string
 class h :
	 def __str__(self):
	    return xxx
     		则 a = h()
			结果返回xxxx
 			Print(a)时输出xxx 
  1. __ bytes behavior of (self) is defined as () call bytes __
  2. __ hash behavior of (self) is defined as hash () call __
  3. __ bool __ (self) is defined as behavior when calling bool (), should return True or False
  4. __ format __ (self, format_spec) define the behavior when the format () call
    attributes related methods
  5. __ getattr __ (self, name) is defined when the user is trying to get a nonexistent property act
  6. __ getattribute __ (self, name) is defined when the behavior of the class attribute is accessed
  7. __ setattr (self, name, value) when the behavior when a property is set __
  8. __ delattr behavior of (self, name) is defined when a property is deleted __
  9. __ dir (self) Defines the dir () behavior is called __
  10. __ get (self, instance, owner) when the behavior is defined descriptor values ​​are acquired __
  11. __ set (self, instance, value) when the behavior is defined descriptor values ​​are changed __
  12. __ delete __ (self, instance) defined descriptor values ​​when the behavior is deleted

Comparison operators

__ lt __ (self, other) is defined smaller than the number of acts: x <y calls X .__ lt __ (Y)
__ Le __ (Self, OTHER) defines less number of acts: x <= y calls x .__ le __ (y)
__ eq __ (self, other) to define equal number of acts: x == y call the X-.__ EQ __ (the y-)
__ ne __ behavior (self, other) define unequal numbers: x = y call the X-.__ ne __ (the y-)!
__ gt __ (self, other) is defined greater than the number of acts: x> y calls X .__ gt __ (Y)
__ GE __ (Self, OTHER) defines greater than or equal number of acts: x> = y calls x .__ ge __ (y)

Arithmetic operators

__ add __ (self, other) to define additional behaviors: +
__ Sub __ (Self, OTHER) defined subtraction behavior: -
__ MUL __ (Self, OTHER) defined multiplication behavior: *
__ truediv __ (Self, OTHER) define true division behavior: /
__ floordiv (Self, OTHER) defines the integer division behavior __: //
__ MOD (Self, OTHER) defined modulo algorithm behavior __:%
__ behavior of divmod __ (self, other) is defined as being divmod () call
__ pow __ (self, other [ , modulo]) is defined as the power () behavior when the call or ** operation
__ lshift __ (self, other) is defined by bit left shift behavior: <<
__ RSHIFT __ (Self, OTHER) defined bitwise right shift behavior: >>
__ and __ (Self, OTHER) defined bitwise behavior and operation: &
__ XOR __ (Self, OTHER) defines a bitwise XOR operation behavior: ^
__ or __ (Self, OTHER ) is defined by behavior or bit operations: |

Inverse operation (similar to the operation method)

__ radd __ (self, other) when operands (left operation target) does not support this operation is called
__ rsub __ (self, other) when operands (left operation target) does not support this operation is called
__ rmul__ (self, other) is called when the operands (left operation target) does not support this operation when
__ rtruediv __ (self, other) when operands (left operation target) does not support this operation is called
__ rfloordiv __ (self , other) is called when the operands (left operation target) does not support this operation when
__ rmod __ (self, other) when operands (left operation target) does not support this operation is called
__ rdivmod __ (self, other ) when operands (left operation target) does not support this operation is called
__ rpow __ (self, other) when operands (left operation target) does not support this operation is called
__ rlshift __ (self, other) when is called when the object is computed (operation target left) does not support this operation
__ rrshift __ (self, other) is called when the object is computed (operation target left) does not support this operation
__ rxor __ (self, other) when the object is computed (operation target left) does not support this operation is called
__ ror __ (self, other) when the object is computed (operation target left) does not support this operation is called

Incremental assignment operator

__ iadd __ (self, other) is defined assignment behavior additions: + =
__ isub __ (Self, OTHER) defines an assignment behavior subtraction: - =
__ IMUL __ (Self, OTHER) defines an assignment behavior multiplication: * =
__ itruediv __ (Self, other) defines assignment true division behavior: / =
__ ifloordiv __ (Self, other) define the behavior of the assignment integer division: // =
__ IMODs __ (Self, other) is defined assignment behavior modulo algorithm:% =
__ ipow __ (Self, other [, modulo]) define behavior assignment exponentiation: ** =
__ __ ilshift (Self, OTHER) is defined by the assignment bit left shift behavior: << =
__ __ irshift (Self, OTHER) defined by a shift bit assignment Right behavior: >> =
__ IAND __ (Self, OTHER) defines the assignment bit and behavior operation: & =
__ ixor __ (Self, OTHER) defined assignment bitwise XOR operation behavior: ^ =
__ IOR __ (Self, OTHER) assignment is defined by behavior or bit operations: | =

Unary operator

__ NEG __ behavior (self) defines a positive sign: + X
__ POS __ behavior (self) defines a negative sign: the -X-
__ ABS __ (self) defines the behavior when the ABS () call
__ Rate History For Converting __ (self) defined bitwise anti behavior: ~ x

Type Conversion

__ complex __ (self) is defined as the complex behavior (need to return the appropriate value) when calling ()
__ int __ (Self) is defined as the behavior when calling int () (need to return the appropriate value)
__ float __ (Self) is defined when the float () call behavior (needs to return an appropriate value)
__ __ round (Self [, n-]) is defined as the behavior is called round () (need to return an appropriate value)

__ index__(self)

  1. When an object is applied in the slice expression achieved cast plastic
  2. If you define a custom value type may be used in the slice, you should define __ index__
  3. __ __ If the index is defined, __ int__ also need to be defined, and returns the same value

Context Management (with statement)

  1. __ enter __ (self) 1. custom initialization behavior when using with statement
  2. __ name after enter__ with the return value of the statement as binding targets or
  3. __ exit__(self, exc_type, exc_value, traceback)
  4. When a code block is defined to be executed or terminated context manager should do
  5. Generally handles exceptions, do cleanup routine or blocks of code after the finished
    container type (typically for operating the containers)
  6. __ len __ (self) Defines the behavior is () call len (returns the length of the container ships and the like)
  7. __ __ (self, key) Gets the container defines the behavior specified element getitem, equivalent to self [key]
  8. __ setitem __ (self, key, value) defines the behavior of the container provided the specified element, corresponding to self [key] = value
  9. __ __ (self, key) to delete the definition of container in the specified element delitem behavior corresponds del self [key]
  10. __ iter __ (self) element in the iteration is defined as the behavior of the container
  11. __ reversed behavior of (self) is defined as () call reversed __
  12. __ contains __ (self, item) as defined behavior when using the operator (in or not in) a member of the test

Custom container

If the varactor is not necessary to define a custom __len__ __getitem__ method and
if the container needs to define a variable __getitem__ __len__ and methods as well as methods __setitem__ and __delitem__

Examples of customizing a custom list immutable, required to record a number of times each element is accessed

class mylist:
	del __init__(self,*args):
		self.values = [x for x in args]    #将*args的元素放入列表中
#(x for x in args) 是一个列表推导式,,,
        self.count = {}.fromkeys(range(len(self.values)),0)
	def __len__(self):
		return len (self.values)
	def __getitem__(self,key):
		self.count[key] += 1
		return self.values[key]

Published 14 original articles · won praise 31 · views 4720

Guess you like

Origin blog.csdn.net/GuanFuXinCSDN/article/details/104315197