Operations are required for getting started with python, while operations are required for getting started with python.

Source: Internet
Author: User

Operations are required for getting started with python, while operations are required for getting started with python.

Here, we provide methods and techniques that are often used in python development. If you have any questions, please correct them.

Key points: In-development class and variable feature query, the type is class, the use of assertions, and the depth of replication judgment.

Python script files are coded in UTF-8, so consider whether text files are coded in UTF-8 when Chinese characters are found to be garbled.

If you want to specify different codes, you need to add such a comment in the header of the source code file:

# -*- coding: utf-8 -*-

If python runs in linux and unix systems, add the following in the first line of the source code:

#!/usr/bin/python3

How can I obtain the content of various modules, variables, and classes in python?

In python, the Helper group query can be obtained through the Variable _ all __,__ dict __, function help (), dir.

If _ all _ is defined in a class or module, it generally contains externally callable features. If no value is assigned, the feature is automatically filled with features starting with a non-underline. If no parameter _ all _ python exists, the AttributeError attribute is incorrect.

_ Dict _ generally provides features (including attributes and methods) defined in a class or module, and uses tuples to represent parameters and parameter values (parameters, parameter value or description)

List _ dict _ view

>>> list.__dict__2 mappingproxy({'__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>, '__lt__': <slot wrapper '__lt__' of 'list' objects>, '__le__': <slot wrapper '__le__' of 'list' objects>, '__eq__': <slot wrapper '__eq__' of 'list' objects>, '__ne__': <slot wrapper '__ne__' of 'list' objects>, '__gt__': <slot wrapper '__gt__' of 'list' objects>, '__ge__': <slot wrapper '__ge__' of 'list' objects>, '__iter__': <slot wrapper '__iter__' of 'list' objects>, '__init__': <slot wrapper '__init__' of 'list' objects>, '__len__': <slot wrapper '__len__' of 'list' objects>, '__getitem__': <method '__getitem__' of 'list' objects>, '__setitem__': <slot wrapper '__setitem__' of 'list' objects>, '__delitem__': <slot wrapper '__delitem__' of 'list' objects>, '__add__': <slot wrapper '__add__' of 'list' objects>, '__mul__': <slot wrapper '__mul__' of 'list' objects>, '__rmul__': <slot wrapper '__rmul__' of 'list' objects>, '__contains__': <slot wrapper '__contains__' of 'list' objects>, '__iadd__': <slot wrapper '__iadd__' of 'list' objects>, '__imul__': <slot wrapper '__imul__' of 'list' objects>, '__new__': <built-in method __new__ of type object at 0x000000005BBAF530>, '__reversed__': <method '__reversed__' of 'list' objects>, '__sizeof__': <method '__sizeof__' of 'list' objects>, 'clear': <method 'clear' of 'list' objects>, 'copy': <method 'copy' of 'list' objects>, 'append': <method 'append' of 'list' objects>, 'insert': <method 'insert' of 'list' objects>, 'extend': <method 'extend' of 'list' objects>, 'pop': <method 'pop' of 'list' objects>, 'remove': <method 'remove' of 'list' objects>, 'index': <method 'index' of 'list' objects>, 'count': <method 'count' of 'list' objects>, 'reverse': <method 'reverse' of 'list' objects>, 'sort': <method 'sort' of 'list' objects>, '__doc__': "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"})

Dir () lists all available feature attributes without values and attribute descriptions:

List View with dir ()

1 >>> dir(list)2 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Generally, you can use _ dict _ and dir (). Of course, you also need help () to view detailed documents (in fact, the content in _ doc ):

List View with help ()

help(list)Help on class list in module builtins:class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(self, value, /) |  Return self+value. | | __contains__(self, key, /) |  Return key in self. | | __delitem__(self, key, /) |  Delete self[key]. | | __eq__(self, value, /) |  Return self==value. | | __ge__(self, value, /) |  Return self>=value. | | __getattribute__(self, name, /) |  Return getattr(self, name). | | __getitem__(...) |  x.__getitem__(y) <==> x[y] |-- More --

If we create an object a = list () and want to obtain the features and methods of object a, we also use dir () and help ().

It should be emphasized that the power of dir () and help () is not only the ability to view classes, but also the variables we define. In this way, we can get more content in the encoding process.

Search for methods contained in variable a = 1

>>> a=1>>> dir(a)['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']>>> help(a)Help on int object:class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 | | Methods defined here: | | __abs__(self, /) |  abs(self) | | __add__(self, value, /) |  Return self+value. | | __and__(self, value, /) |  Return self&value. |-- More --

Search for variables and Object Types

In python, except for using dir (), help () ,__ all __,__ dict _ to view the content of the original definition design, you can use many defined features to obtain more information:

Method for obtaining the variable type and object type:

Query variables and class types through _ class _

>>> a =1>>> a.__class__<class 'int'>>>> b = 1.0>>> b.__class__<class 'float'>>>> c = ''>>> c.__class__<class 'str'>>>> d = list()>>> d.__class__<class 'list'>>>> e = tuple()>>> e.__class__<class 'tuple'>>>> f = dict()>>> f.__class__<class 'dict'>>>> list.__class__<class 'type'>>>> dict.__class__<class 'type'>>>> tuple.__class__<class 'type'>>>> object.__class__<class 'type'>>>> None.__class__<class 'NoneType'>

Through the above Code, we found that if the class is type, it is actually a class definition, and if it is other, it is an object.

Have you ever thought that the basic variables in python are also objects?

In general languages, our types are classified into integer, floating point, string, and so on. However, in python, these types are actually defined in the form of classes, and classes inherit from top-level superclasses.

Use _ class _ to view the type, __bases _ to view the superclass

>>> a = 1>>> a.__class__<class 'int'>>>> int.__class__<class 'type'>>>> str.__class__<class 'type'>>>> bool.__class__<class 'type'>>>> list.__class__<class 'type'>>>> dict.__class__<class 'type'>>>> tuple.__class__<class 'type'>>>> type.__class__<class 'type'>>>> object.__class__<class 'type'>>>> type.__bases__(<class 'object'>,)>>> int.__bases__(<class 'object'>,)>>> str.__bases__(<class 'object'>,)>>> bool.__bases__(<class 'int'>,)>>> float.__bases__(<class 'object'>,)>>> object.__bases__()>>>

No. The types we use are actually classes, except that bool inherits the class int, and others inherit the super class object. The object class does not have superclasses. It should be said that type is a type class! Of course, the None type is NoneType, but NoneType is not a class. This means that None is a null value.

Content contained in the type class and content contained in the object class

>>> dir(type)['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro']>>> dir(object)['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Is and id () Let us see the hidden relationship between variables!

We all know that python has a weak type of convenience in use. Of course, in python, there is only one variable with the same value! Why? This is because they all point to the same memory address. You can think of these variables as memory addresses, our assignment only changes the memory address they direct !!

It is helpful to understand python from the perspective of pointers. Variables themselves store pointers. if you can understand this, the python variables and memory collection mechanisms can be well understood and used.

The role of A is B operation is to determine whether A is B. If it is true, it means that A and B are the same object. If it is false, it means that A and B are not the same object.

Id (A) is used to determine the id serial number of A in the memory.

The following describes the related phenomena in python in detail:

1. in python, although A and B are the same object, after assigning A value to A, A and B are the same object, in python, the value assignment changes the address pointed to by A to the address of another object. At this time, unlike the address in B, the value of the object caused by B will not be affected by the value assignment by.

2. the IDs of the same object in python may be different, because when there is no variable pointing to this address, the python memory will automatically clear the object. The object with the same value may be a new object created after the previous object is automatically cleared.

In the first case, we first determine the values of True and False and the number of the object IDs that are provided by the system, even if these value objects are not cleared by variables using python memory, they will not be cleared!

Id is used to determine whether the value object in the value and Boolean value is a built-in object.

>>> id(True)1538937056>>> id(False)1538937088>>> id(False) - id(True)32>>> id(-5)1539416992>>> id(-6)1667933956912>>> id(-4)1539417024>>> id(-4)-id(-5)32>>> id(-3)-id(-4)32>>> id(-3)1539417056>>> id(-2)1539417088>>> id(-2) - id(-3)32>>> id(255)1539425312>>> id(256)1539425344>>> id(256) - id(255)32>>> id(257)1667904611440>>> id(1.0)1667904643192

You will find that numbers-5 to 256 are continuous, and their adjacent id values differ by 32, which means they represent the values. The value returned by the id is the value of their logical memory address in python. In different python processes, the id values returned by these same value objects are consistent. The numeric values smaller than-5 or greater than 256, decimal places, and strings larger than a single character are value objects created by python when users use them, the IDS of the same values in different python processes are different! When other values are not in use, some will be cleared by the python memory cleanup program to release the memory!

Of course, there are many objects, classes, and functions in python that are self-created by python and will not be cleared by the memory cleanup program because they are not used. For example, int, None, dict, and list.

It is not worth mentioning that None is True. And the return value of id (None) is 1538983120. This indicates that, unlike other scripts (such as javascript), None is a null value and is a unique null value object. All the None in the program are equal. Values stored in the same memory address.

In many cases, we can use is to determine whether two variables point to the value of the same memory address block.

Python provides additional processing methods for global variables, local variables, and external variables.

If a function defines a variable with the same external name, how can we obtain an external variable within the function? In other languages, we all know that local variables overwrite external variables with the same name. Although this logic is also used in python, it provides three functions so that we can obtain variable values with the same name defined in different scopes.

Globals () Get all global variable values

Locals () Get all local variable values

Nonlocals () obtain all external variable values (because python supports function nesting, this can be used if an internal function wants to obtain the local variable value of an external function)

Obtain the variable with the same name from the global variable in the local variable.

>>> a = 234>>> globals(){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 234}>>> def s():...  a = 'hello'...  print(locals())...>>> s(){'a': 'hello'}>>> def u():...  a = 'world'...  c = globals()['a']...  print(c)...>>> u()234

As shown in the code above, in function u (), the value of a is 'World', the value of a in global variables is 234, and function s () the value of local variable a is 'Hello'. Using globals () [variable name], you can obtain the value of a variable with the same name in the global variable.

Locally change the global variable value with the same name in the previous Code

>>> def e():...  a = 'sdf'...  globals()['a'] = a...>>> e()>>> a'sdf'>>>

The above is a basic introduction to python. The operation is all the content that I have shared with you. I hope to give you a reference and support for the help house.

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.