Underline in python skills (2) and underline in python skills

Source: Internet
Author: User

Underline in python skills (2) and underline in python skills

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__()

 

Classes with similar behavior methods and functions

Makes the instance of the class callable-just like a function can be called-by defining__call__()Method.

Serial number Purpose Code written Python actual call
  Call an instance like a function. my_instance() my_instance.__call__()

zipfileThe module defines a passwordDecryption Encrypted ZipFile class. This zipDecryptionThe algorithm must be saved during decryption. By defining the encryptor as a class, we can maintain the state in a single instance of the decryptor class. Status in__init__()Method, if the fileEncryptedThen update. However, because this class is "callable" like a function, you can use the instancemap()The code for passing in the first parameter of the function is as follows:

# excerpt from zipfile.py class _ZipDecrypter: def __init__(self, pwd): self.key0 = 305419896 ① self.key1 = 591751049 self.key2 = 878082192 for p in pwd: self._UpdateKeys(p) def __call__(self, c): ② assert isinstance(c, int) k = self.key2 | 2 c = c ^ (((k * (k^1)) >>  & 255) self._UpdateKeys(c) return c zd = _ZipDecrypter(pwd) ③ bytes = zef_file.read(12) h = list(map(zd, bytes[0:12])) ④
Classes with similar behavior patterns and Sequences

If a class appears as a container of a series of values -- that is, if it is meaningful for a class to "include" A value -- then it may be necessary to define the following special method, let it behave in a similar way as a sequence.

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)

cgiModule in itsFieldStorageThese methods are used to indicate all form fields or query parameters submitted to a dynamic web page.

# A script which responds to http://example.com/search?q=cgi import cgi fs = cgi.FieldStorage() if 'q' in fs: ① do_search() # An excerpt from cgi.py that explains how that works class FieldStorage: . . . def __contains__(self, key): ② if self.list is None: raise TypeError('not indexable') return any(item.name == key for item in self.list) ③ def __len__(self): ④ return len(self.keys()) ⑤
Classes with similar behavior methods and dictionaries

Based on the previous section, we can not onlyin"Operator andlen()The function can return values based on keys like full-function dictionaries.

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)

cgiModuleFieldStorageClasses also define these special methods, that is, they can be encoded as follows:

# A script which responds to http://example.com/search?q=cgi import cgi fs = cgi.FieldStorage() if 'q' in fs: do_search(fs['q']) ① # An excerpt from cgi.py that shows how it works class FieldStorage: . . . def __getitem__(self, key): ② if self.list is None: raise TypeError('not indexable') found = [] for item in self.list: if item.name == key: found.append(item) if not found: raise KeyError(key) if len(found) == 1: return found[0] else: return found
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__()

? If__lt__()Method but not defined__gt__()Method.__lt__()Method. However, Python does not combine methods. For example, if__lt__()Method and__eq()__And try to test whetherx <= y, Python will not be called in order__lt__()And__eq()__. It will only call__le__()Method.

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.

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.