Underline in Python --- full explanation, python underline ---

Source: Internet
Author: User

Underline in Python --- full explanation, python underline ---
 

Python uses underscores (_) as the prefix and suffix of variables to specify special variables.

_ Xxx cannot be imported using 'from module import *'

_ Xxx _ system definition name

_ Private variable name in xxx class

Core style: Avoid using underscores as the start of variable names.

 

Because underlines have special meanings for the interpreter and are symbols used by built-in identifiers, we recommend that programmers avoid using underscores as the beginning of the variable name. Generally, variable name_xxx is considered as "private" and cannot be used outside the module or class. When the variable is private, it is a good habit to use _ xxx to represent the variable. Because the variable name _ xxx _ has a special meaning for Python, this naming style should be avoided for common variables.

Member variables starting with "single underline" are called protection variables, meaning that only class objects and subclass objects can access these variables themselves;
"Double underline" begins with a private member, meaning that only the class object can access the data, and even the subclass object cannot access the data.

A class attribute that starts with a single underscore (_ foo) represents a class attribute that cannot be accessed directly. It must be accessed through the interface provided by the class. It cannot be imported using "from xxx import; (_ foo) starting with a double underline represents a private member of the class; (_ foo _) Starting with and ending with a double underline represents a special identifier for special methods in python, for example, _ init _ () indicates the constructor of the class.

Now let's summarize all the system-defined attributes and methods. Let's take a look at the reserved attributes:

>>> Class1. _ doc _ # type help information 'class1 Doc. '>>> Class1. _ name _ # type name 'class1'> Class1. _ module _ # module of the type' _ main _ '> Class1. _ bases _ # base class inherited by the type (<type 'object'>,) >>> class1. _ dict _ # type dictionary, which stores information about all types of members. <Dictproxy object at 0x00D3AD70> Class1 (). _ class _ # type <class '_ main __. class1 '>>>> Class1 (). _ module _ # module of the Instance type '_ main _'> Class1 (). _ dict _ # object dictionary, which stores information about all instance members. {'I': 1234}
The following describes the retention method. You can classify the retention method as follows:
Basic Method of class
Serial number Purpose Code written Python actual call
Initialize an instance x = MyClass() x.__init__()
String "official" Representation repr(x) x.__repr__()
"Informal" value of the string str(x) x.__str__()
"Informal" value of the byte array bytes(x) x.__bytes__()
Format the string value format(x,format_spec) x.__format__(format_spec)
Class similar to the iterator in behavior mode
Serial number Purpose Code written Python actual call
Traverse a sequence iter(seq) seq.__iter__()
Get the next value from the iterator next(seq) seq.__next__()
Create an iterator in reverse order reversed(seq) seq.__reversed__()
Calculation attribute
Serial number Purpose Code written Python actual call
Obtain a computing attribute (unconditional) x.my_property x.__getattribute__('my_property')
Obtain a computing attribute (Backup) x.my_property x.__getattr__('my_property')
Set an attribute x.my_property = value x.__setattr__('my_property',value)
Delete an attribute del x.my_property x.__delattr__('my_property')
List all attributes and Methods dir(x) x.__dir__()

 

Serial number Purpose Code written Python actual call
  Sequence length len(seq) seq.__len__()
  Check whether a sequence contains specific values. x in seq seq.__contains__(x)

 

Serial number Purpose Code written Python actual call
  Obtain the value through the key x[key] x.__getitem__(key)
  Set the value through the key x[key] = value x.__setitem__(key,value)
  Deletes a key-value pair. del x[key] x.__delitem__(key)
  Provide default values for missing keys x[nonexistent_key] x.__missing__(nonexistent_key)

 

Comparable classes

I used this content in the previous section to separate it into sections because the "Compare" operation is not limited to numbers. Many data types can be compared-strings, lists, and even dictionaries. If you want to create your own classes and make the comparison between objects meaningful, you can use the following special method for comparison.

 

Serial number Purpose Code written Python actual call
  Equal x == y x.__eq__(y)
  Not equal x != y x.__ne__(y)
  Less x < y x.__lt__(y)
  Less than or equal x <= y x.__le__(y)
  Greater x > y x.__gt__(y)
  Greater than or equal x >= y x.__ge__(y)
  Boolean true value in context if x: x.__bool__()

 

Serializable classes

 

Python supports serialization and deserialization of any object. (Most Python references refer to this process as "pickling" and "unpickling "). This technology makes sense for saving the status as a file and restoring it later. Pickling is supported for all built-in data types. If you have created a custom class and want it to be pickle, read the pickle protocol to understand when and how the following special methods are called.

 

Serial number Purpose Code written Python actual call
  Copying custom objects copy.copy(x) x.__copy__()
  Deep replication of custom objects copy.deepcopy(x) x.__deepcopy__()
  Get the object status before pickling pickle.dump(x, file) x.__getstate__()
  Serialize an object pickle.dump(x, file) x.__reduce__()
  Serialize an object (New pickling Protocol) pickle.dump(x, file,protocol_version) x.__reduce_ex__(protocol_version)
* Controls how objects are created during the unpickling Process x = pickle.load(file) x.__getnewargs__()
* Restore the object status after unpickling x = pickle.load(file) x.__setstate__()

 

* To recreate a serialized object, Python needs to create a new object that looks the same as the serialized object, and then set all attributes of the new object.__getnewargs__()Method to Control the creation process of the new object, and__setstate__()Method to Control the restoration of attribute values.

 

You can withClasses used in Block

 

withThe language block defines the runtime context.withThe statement will "enter" the context, and the last statement in the block will "exit" the context.

 

Serial number Purpose Code written Python actual call
  Before enteringwithPerform some special operations in block Language with x: x.__enter__()
  ExitwithPerform some special operations in block Language with x: x.__exit__()

 

Below iswith fileHabitual usage:

# excerpt from io.py: def _checkClosed(self, msg=None):     '''Internal: raise an ValueError if file is closed     '''     if self.closed:         raise ValueError('I/O operation on closed file.'                          if msg is None else msg)  def __enter__(self):     '''Context management protocol.  Returns self.'''     self._checkClosed()                                ①     return self                                        ②  def __exit__(self, *args):     '''Context management protocol.  Calls close()'''     self.close()                                       ③

 

 

? The__exit__()Methods will always be called, even inwithExceptions are thrown in the block. In fact, if an exception is thrown, the exception information will be passed__exit__()Method. For more details, see the With State context Environment Manager.

 

What's amazing

 

If you know what you are doing, you can almost fully control how the class is compared, how the attributes are defined, and what type the class subclass is.

 

Serial number Purpose Code written Python actual call
  Class Constructor x = MyClass() x.__new__()
* Destructor del x x.__del__()
  Only certain attributes of a specific set are defined.   x.__slots__()
  Custom hash value hash(x) x.__hash__()
  Obtains the value of an attribute. x.color type(x).__dict__['color'].__get__(x, type(x))
  Set the value of an attribute x.color = 'PapayaWhip' type(x).__dict__['color'].__set__(x, 'PapayaWhip')
  Delete an attribute del x.color type(x).__dict__['color'].__del__(x)
  Instance your class that controls whether an object is the object isinstance(x, MyClass) MyClass.__instancecheck__(x)
  Determines whether a class is a subclass of this class. issubclass(C, MyClass) MyClass.__subclasscheck__(C)
  Determines whether a class is a subclass of the abstract base class. issubclass(C, MyABC) MyABC.__subclasshook__(C)

 

In python, the double-underline is the name defined by some systems, so that python can perform some operations with a better elegant syntax. In essence, there are still some functions and variables, which are no different from other functions and variables.
For example, x. _ add _ (y) is equivalent to x + y.
Some of them are very common, and some may be relatively biased. Here we will list them, take notes, and forget them.
X. _ contains _ (y) is equivalent to y in x. This function is available in containers such as list, str, dict, and set.
_ Base __, _ bases __, _ mro __, about class inheritance and function search path.
Class. _ subclasses _ (), returns the subclass list.
X. _ call _ (...) = x (...)
X. _ cmp _ (y) = cmp (x, y)
X. _ getattribute _ ('name') = x. name = getattr (x, 'name'), called earlier than _ getattr _
X. _ hash _ () = hash (x)
X. _ sizeof _ (), the number of bytes of x in the memory. If x is a class, it should be x. _ basicsize __
X. _ delattr _ ('name') = del x. name
_ Dictoffset _ attribute tells you the offset to where you find the pointer to the _ dict _ object in any instance object that has one. It is in bytes.
_ Flags __, returns a number to determine whether the type can be serialized (if it's a heap type), _ flags _ & 512
S. _ format __, which is useful for some classes
X. _ getitem _ (y) = x [y], and _ setitem __. some unchangeable types such as set and str do not have _ setitem __
X. _ getslice _ (I, j) = x [I: j]. If you have any questions, x = '000000', x [: 2]. How can this problem be solved?
_ Subclasscheck _ (), check if a class is subclass
_ Instancecheck _ (), check if an object is an instance
_ Itemsize __, These fields allow calculating the size in bytes of instances of the type. 0 is a variable length, not 0 is a fixed length
X. _ mod _ (y) = x % y, x. _ rmod _ (y) = y % x
X. _ module _, module of x
X. _ mul _ (y) = x * y, x. _ rmul _ (y) = y * x

_ Reduce __, _ performance_ex _, for pickle

When _ slots _ is used, the class becomes static. If _ dict __is absent, attributes cannot be added to the instance.

_ Getattr _ this function is called when the common search attribute cannot be found.

_ Setattr _ replaces the normal value assignment operation. If this function is available, this function is called. To call the normal value assignment method, use object. _ setattr _ (self, name, value)

_ Delattr _ Same _ setattr __, called when del obj. name is meaningful

Related Article

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.