中英文模式阅读
中文模式阅读
英文模式阅读

Python Code Examples

Python is a general purpose programming language which is dynamically typed, interpreted, and known for its easy readability with great design principles.
是一种通用编程语言,它具有很好的设计原则,因其易于阅读而动态地输入,解释和着名。

freeCodeCamp has one of the most popular courses on Python. It's completely free (and doesn't even have any advertisements). You can
freeCodeCamp是Python上最受欢迎的课程之一。它是完全免费的(甚至没有任何广告)。您可以watch it on YouTube here.

Some general information about floating point numbers and how they work in Python, can be found
可以找到有关浮点数以及它们如何在Python中工作的一些常规信息here.

Nearly all implementations of Python follow the IEEE 754 specification: Standard for Binary Floating-Point Arithmetic. More information found on the
几乎所有Python的实现都遵循IEEE 754规范:二进制浮点运算标准。更多信息发现于IEEE site.

Float objects can be created using
可以使用创建浮动对象floating point literals:

>>> 3.14
3.14
>>> 314\.    # Trailing zero(s) not required.
314.0
>>> .314    # Leading zero(s) not required.
0.314
>>> 3e0
3.0
>>> 3E0     # 'e' or 'E' can be used.
3.0
>>> 3e1     # Positive value after e moves the decimal to the right.
30.0
>>> 3e-1    # Negative value after e moves the decimal to the left.
0.3
>>> 3.14e+2 # '+' not required but can be used for exponent part.
314.0

Numeric literals do not contain a sign, however creating negative float objects is possible by prefixing with a unary
数字文字不包含符号,但是可以通过为一元添加前缀来创建负浮点对象- (minus) operator with no space before the literal:
(减号)运算符在文字前没有空格:

>>> -3.141592653589793
-3.141592653589793
>>> type(-3.141592653589793)
<class 'float'>

Likewise, positive float objects can be prefixed with a unary
同样,正浮动对象可以以一元为前缀+ (plus) operator with no space before the literal. Usually
(加)运算符在字面之前没有空格。平时+ is omitted:
省略:

>>> +3.141592653589793
3.141592653589793

Note that leading and trailing zero(s) are valid for floating point literals.
请注意,前导零和尾随零对浮点文字有效。

>>> 0.0
0.0
>>> 00.00
0.0
>>> 00100.00100
100.001
>>> 001e0010      # Same as 1e10
10000000000.0

The
float constructor is another way to create
是另一种创造方式float objects.
对象。

Creating
创建float objects with floating point literals is preferred when possible:
在可能的情况下,首选具有浮点文字的对象:

>>> a = 3.14         # Prefer floating point literal when possible.
>>> type(a)
<class 'float'>
>>> b = int(3.14)    # Works but unnecessary.
>>> type(b)
<class 'float'>

However, the float constructor allows for creating float objects from other number types:
但是,float构造函数允许从其他数字类型创建float对象:

>>> a = 4
>>> type(a)
<class 'int'>
>>> print(a)
4
>>> b = float(4)
>>> type(b)
<class 'float'>
>>> print(b)
4.0
>>> float(400000000000000000000000000000000)
4e+32
>>> float(.00000000000000000000000000000004)
4e-32
>>> float(True)
1.0
>>> float(False)
0.0

The
float constructor will also make
构造函数也会float objects from strings that represent number literals:
来自表示数字文字的字符串的对象:

>>> float('1')
1.0
>>> float('.1')
0.1
>>> float('3.')
3.0
>>> float('1e-3')
0.001
>>> float('3.14')
3.14
>>> float('-.15e-2')
-0.0015

The
float constructor can also be used to make numeric representations of
构造函数也可用于进行数值表示NaN (Not a Number), negative
(不是数字),否定infinity and
infinity (note that strings for these are case insensitive):
(请注意,这些字符串不区分大小写):

>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('infinity')
inf
>>> float('-infinity')
-inf

bool() is a built-in function in Python 3. This function returns a Boolean value, i.e. True or False. It takes one argument,
是Python 3中的内置函数。此函数返回一个布尔值,即True或False。这需要一个论点,x.

Arguments {#arguments}

It takes one argument,
这需要一个论点,x.
x is converted using the standard
使用标准转换Truth Testing Procedure.

Return Value {#return-value}

If
如果x is false or omitted, this returns
是false或省略,返回False; otherwise it returns
;否则它会返回True.

Code Sample {#code-sample}

print(bool(4 > 2)) # Returns True as 4 is greater than 2
print(bool(4 < 2)) # Returns False as 4 is not less than 2
print(bool(4 == 4)) # Returns True as 4 is equal to 4
print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality doesn't holds
print(bool(4)) # Returns True as 4 is a non-zero value
print(bool(-4)) # Returns True as -4 is a non-zero value
print(bool(0)) # Returns False as it is a zero value
print(bool('dskl')) # Returns True as the string is a non-zero value
print(bool([1, 2, 3])) # Returns True as the list is a non-zero value
print(bool((2,3,4))) # Returns True as tuple is a non-zero value
print(bool([])) # Returns False as list is empty and equal to 0 according to truth value testing

and,
or,
not

Python Docs - Boolean Operations

These are the Boolean operations, ordered by ascending priority:
这些是布尔运算,按升序排序:

OperationResultNotes x or y if x is false, then y, else x (1) x and y if x is false, then x, else y (2) not x if x is false, then True, else False (3).
OperationResultNotes x或y如果x为假,则为y,否则x(1)x和y如果x为假,则为x,否则y(2)不为x如果x为假,则为True,否则为False(3)。

Notes:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is True.
  3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

Examples: {#examples-}

not: {#not-}

>>> not True
False
>>> not False
True

and: {#and-}

>>> True and False    # Short-circuited at first argument.
False
>>> False and True    # Second argument is evaluated.
False
>>> True and True     # Second argument is evaluated.
True

or: {#or-}

>>> True or False    # Short-circuited at first argument.
True
>>> False or True    # Second argument is evaluated.
True
>>> False or False   # Second argument is evaluated.
False

Three commonly used built-in constants:
三种常用的内置常量:

  • True: The true value of the bool type. Assignments to True raise a SyntaxError .
  • False: The false value of the bool type. Assignments to False raise a SyntaxError .
  • None : The sole value of the type NoneType . None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None raise a SyntaxError .

Other built-in constants:
其他内置常量:

  • NotImplemented: Special value which should be returned by the binary special methods, such as __eg__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type.
  • Ellipsis: Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.
  • __debug__: True if Python was not started with an -o option.

Constants added by the site module. The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.
站点模块添加的常量。站点模块(在启动期间自动导入,除非给出-S命令行选项)将向内置命名空间添加几个常量。它们对交互式解释器shell很有用,不应在程序中使用。

Objects that, when printed, print a message like "Use quit() or Ctrl-D (i.e. EOF) to exit", and when called, raise SystemExit with the specified exit code:
打印时打印消息,如"使用退出()或Ctrl-D(即EOF)退出",并在调用时,使用指定的退出代码引发SystemExit:

  • quit(code=None)
  • exit(code=None)

Objects that, when printed, print a message like "Type license() to see the full license text", and when called, display the corresponding text in a pager-like fashion (one screen at a time):
打印时打印"类型许可证()以查看完整许可证文本"的消息,并在调用时以类似寻呼机的方式显示相应的文本(一次一个屏幕):

  • copyright
  • license
  • credits

A function definition statement does not execute the function. Executing (calling) a function is done by using the name of the function followed by parenthesis enclosing required arguments (if any).
函数定义语句不执行该函数。执行(调用)函数是通过使用函数的名称,后跟括起所需参数(如果有)的括号来完成的。

>>> def say_hello():
...     print('Hello')
...
>>> say_hello()
Hello

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table.
函数的执行引入了用于函数局部变量的新符号表。更准确地说,函数中的所有变量赋值都将值存储在本地符号表中。

On the other hand, variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
另一方面,变量引用首先在本地符号表中查找,然后在封闭函数的本地符号表中查找,然后在全局符号表中查找,最后在内置名称表中查找。因此,全局变量不能直接在函数内赋值(除非在全局语句中命名),尽管可以引用它们。

>>> a = 1
>>> b = 10
>>> def fn():
...     print(a)    # local a is not assigned, no enclosing function, global a referenced.
...     b = 20      # local b is assigned in the local symbol table for the function.
...     print(b)    # local b is referenced.
...
>>> fn()
1
20
>>> b               # global b is not changed by the function call.
10

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called. In this way, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.
调用函数调用的实际参数(参数)在被调用函数的本地符号表中引入。通过这种方式,使用call by value传递参数(其中值始终是对象引用,而不是对象的值)。当函数调用另一个函数时,将为该调用创建一个新的本地符号表。

>>> def greet(s):
...     s = "Hello " + s    # s in local symbol table is reassigned.
...     print(s)
...
>>> person = "Bob"
>>> greet(person)
Hello Bob
>>> person                  # person used to call remains bound to original object, 'Bob'.
'Bob'

The arguments used to call a function cannot be reassigned by the function, but arguments that reference mutable objects can have their values changed:
用于调用函数的参数不能由函数重新分配,但引用可变对象的参数可以更改其值:

>>> def fn(arg):
...     arg.append(1)
...
>>> a = [1, 2, 3]
>>> fn(a)
>>> a
[1, 2, 3, 1]

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.
类提供了将数据和功能捆绑在一起的方法。创建新类会创建一种新类型的对象,从而允许创建该类型的新实例。每个类实例都可以附加属性以保持其状态。类实例还可以具有用于修改其状态的方法(由其类定义)。

Compared with other programming languages, Python's class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++.
与其他编程语言相比,Python的类机制添加了具有最少新语法和语义的类。它是C ++中的类机制的混合体。

Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name.
Python类提供面向对象编程的所有标准功能:类继承机制允许多个基类,派生类可以覆盖其基类或类的任何方法,并且方法可以调用具有相同名称的基类的方法。

Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.
对象可以包含任意数量和种类的数据。与模块一样,类也参与Python的动态特性:它们是在运行时创建的,可以在创建后进一步修改。

Class Definition Syntax : {#class-definition-syntax-}

The simplest form of class definition looks like this:
最简单的类定义形式如下所示:

class ClassName:
    <statement-1>
        ...
        ...
        ...
    <statement-N>

Class Objects: {#class-objects-}

Class objects support two kinds of operations: attribute references and instantiation.
类对象支持两种操作:属性引用和实例化。

Attribute references use the standard syntax used for all attribute references in Python:
属性引用使用Python中所有属性引用使用的标准语法:obj.name. Valid attribute names are all the names that were in the class's namespace when the class object was created. So, if the class definition looked like this:
。有效的属性名称是创建类对象时类的命名空间中的所有名称。所以,如果类定义看起来像这样:

class MyClass:
    """ A simple example class """
    i = 12345

    def f(self):
        return 'hello world'

Then
然后MyClass.i and
MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of
是有效的属性引用,分别返回一个整数和一个函数对象。也可以将类属性赋值给,因此可以更改其值MyClass.i by assignment.
通过转让。__doc__ is also a valid attribute, returning the docstring belonging to the class:
也是一个有效的属性,返回属于该类的docstring:"A simple example class".

Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):
类实例化使用函数表示法。只是假装类对象是一个无参数函数,它返回一个新的类实例。例如(假设上述类):

x = MyClass()

Creates a new instance of the class and assigns this object to the local variable x.
创建类的新实例,并将此对象分配给局部变量x。

The instantiation operation ("calling" a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named
实例化操作("调用"类对象)创建一个空对象。许多类喜欢创建具有针对特定初始状态定制的实例的对象。因此,类可以定义一个名为的特殊方法 init (), like this:
(), 像这样:

def __init__(self):
    self.data = []

When a class defines an
当一个类定义一个__init__() method, class instantiation automatically invokes
方法,类实例化自动调用__init__() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:
对于新创建的类实例。因此,在此示例中,可以通过以下方式获取新的初始化实例:

x = MyClass()

Of course, the
当然,__init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to
方法可能具有更大灵活性的论据。在这种情况下,将赋予类实例化运算符的参数传递给__init__(). For example,
。例如,

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
              ...

x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

It is generally good practice for you not to mix tabs and spaces when coding in Python. Doing this can possibly cause a
在Python中编码时,通常不要混合制表符和空格。这样做可能会导致TabError, and your program will crash. Be consistent when you code - choose either to indent using tabs or spaces and follow your chosen convention throughout your program.
,你的程序将崩溃。在编码时保持一致 - 选择使用制表符或空格缩进,并在整个程序中遵循您选择的约定。

Code Blocks and Indentation {#code-blocks-and-indentation}

One of the most distinctive features of Python is its use of indentation to mark blocks of code. Consider the if-statement from our simple password-checking program:
Python最显着的特点之一是使用缩进来标记代码块。考虑我们简单的密码检查程序中的if语句:

if pwd == 'apple':
    print('Logging on ...')
else:
    print('Incorrect password.')

print('All done!')

The lines print('Logging on ...') and print('Incorrect password.') are two separate code blocks. These happen to be only a single line long, but Python lets you write code blocks consisting of any number of statements.
行打印(&#39;登录...&#39;)和打印(&#39;密码错误。&#39;)是两个独立的代码块。这些恰好只有一行,但Python允许您编写由任意数量的语句组成的代码块。

To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python.
要在Python中指示代码块,必须将块的每一行缩进相同的量。我们的示例if-statement中的两个代码块都缩进了四个空格,这是Python的典型缩进量。

In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to. For instance, the final print('All done!') is not indented, and so is not part of the else-block.
在大多数其他编程语言中,缩进仅用于帮助使代码看起来很漂亮。但是在Python中,需要指出语句所属的代码块。例如,最终的打印(&#39;All done!&#39;)没有缩进,因此不是else块的一部分。

Programmers familiar with other languages often bristle at the thought that indentation matters: Many programmers like the freedom to format their code how they please. However, Python indentation rules are quite simple, and most programmers already use indentation to make their code readable. Python simply takes this idea one step further and gives meaning to the indentation.
熟悉其他语言的程序员常常因为缩进很重要而感到愤怒:许多程序员喜欢自由地格式化他们的代码。但是,Python缩进规则非常简单,大多数程序员已经使用缩进来使代码可读。 Python只是将这个想法更进一步,并为缩进赋予了意义。

If/elif-statements {#if-elif-statements}

An if/elif-statement is a generalized if-statement with more than one condition. It is used for making complex decisions. For example, suppose an airline has the following "child" ticket rates: Kids 2 years old or younger fly for free, kids older than 2 but younger than 13 pay a discounted child fare, and anyone 13 years or older pays a regular adult fare. The following program determines how much a passenger should pay:
if / elif语句是具有多个条件的通用if语句。它用于制定复杂的决策。例如,假设航空公司有以下"儿童"机票价格:2岁或以下的儿童免费飞行,2岁以上但13岁以下的儿童支付打折的儿童票价,13岁或以上的任何人支付正常的成人票价。以下计划确定乘客应支付的费用:

# airfare.py
age = int(input('How old are you? '))
if age <= 2:
    print(' free')
elif 2 < age < 13:
    print(' child fare)
else:
    print('adult fare')

After Python gets age from the user, it enters the if/elif-statement and checks each condition one after the other in the order they are given.
在Python从用户开始老化之后,它进入if / elif语句并按照给定的顺序依次检查每个条件。

So first it checks if age is less than 2, and if so, it indicates that the flying is free and jumps out of the elif-condition. If age is not less than 2, then it checks the next elif-condition to see if age is between 2 and 13. If so, it prints the appropriate message and jumps out of the if/elif-statement. If neither the if-condition nor the elif-condition is True, then it executes the code in the else-block.
因此,首先检查年龄是否小于2,如果是,则表明飞行是自由的并且跳出了elif条件。如果age不小于2,则检查下一个elif条件以查看age是否介于2和13之间。如果是,则打印相应的消息并跳出if / elif语句。如果if条件和elif条件都不为True,则它执行else块中的代码。

Conditional expressions {#conditional-expressions}

Python has one more logical operator that some programmers like (and some don't!). It's essentially a shorthand notation for if-statements that can be used directly within expressions. Consider this code:
Python有一个逻辑运算符,一些程序员喜欢(有些不喜欢!)。它本质上是可以直接在表达式中使用的if语句的简写符号。考虑以下代码:

food = input("What's your favorite food? ")
reply = 'yuck' if food == 'lamb' else 'yum'

The expression on the right-hand side of = in the second line is called a conditional expression, and it evaluates to either 'yuck' or 'yum'. It's equivalent to the following:
第二行中=右侧的表达式称为条件表达式,它的计算结果为&#39;yuck&#39;或&#39;yum&#39;。它相当于以下内容:

food = input("What's your favorite food? ")
if food == 'lamb':
   reply = 'yuck'
else:
   reply = 'yum'

Conditional expressions are usually shorter than the corresponding if/else-statements, although not quite as flexible or easy to read. In general, you should use them when they make your code simpler.
条件表达式通常比相应的if / else语句短,但不够灵活或易于阅读。通常,您应该在使代码更简单时使用它们。

There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example,
Python中有八个比较操作。它们都具有相同的优先级(高于布尔操作的优先级)。比较可以任意链接;例如,x < y <= z is equivalent to
相当于x < y and y <= z, except that
, 除了那个y is evaluated only once (but in both cases
仅评估一次(但在两种情况下z is not evaluated at all when
完全没有评估x < y is found to be false).
被发现是假的)。

The following summarizes the comparison operations:
以下总结了比较操作:

OperationMeaning
OperationMeaning<strictly less than
严格不到<=less than or equal to
小于或等于>strictly greater than
严格大于>=greater than or equal to
大于或等于==equal to
等于!=not equal to
不等于is object identity
对象身份is not negated object identity
否定了对象的身份

Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal. The
除了不同的数字类型之外,不同类型的对象永远不会相等。此外,某些类型(例如,函数对象)仅支持简并比较概念,其中该类型的任何两个对象都是不相等的。该<,
<=,
> and
>= operators will raise a
运营商将提出一个TypeError exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.
将复数与另一个内置数值类型进行比较时的异常,当对象具有无法比较的不同类型时,或者在没有定义排序的其他情况下。

Non-identical instances of a class normally compare as non-equal unless the class defines the
除非类定义了类,否则类的非相同实例通常会比较为不相等__eq__()method.
方法。

Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods
除非类定义了足够多的方法,否则无法针对同一类的其他实例或其他类型的对象对类的实例进行排序。__lt__(),
__le__(),
__gt__(), and
,和__ge__() (in general,
(一般来说,__lt__() and
__eq__() are sufficient, if you want the conventional meanings of the comparison operators).
如果你想要比较运算符的常规含义,那就足够了。

The behavior of the
的行为is and
is not operators cannot be customized; also they can be applied to any two objects and never raise an exception.
运营商无法定制;它们也可以应用于任何两个对象,并且永远不会引发异常。

We can also chain
我们也可以连锁< and
> operators together. For instance,
运营商在一起例如,3 < 4 < 5 will return
将返回True, but
但是3 < 4 > 5will not. We can also chain the equality operator. For instance,
将不会。我们也可以链接相等运算符。例如,3 == 3 < 5 will return
将返回True but
3 == 5 < 5 will not.
将不会。

Equality Comparisons - "is" vs "==" {#equality-comparisons-is-vs-}

In Python, there are two comparison operators which allow us to check to see if two objects are equal. The
在Python中,有两个比较运算符允许我们检查两个对象是否相等。该is operator and the
操作员和== operator. However, there is a key difference between them!
运营商。但是,他们之间有一个关键的区别!

The key difference between 'is' and '' can be summed up as:
&#39;是&#39;和&#39;
&#39;之间的关键区别可以概括为:

  • is is used to compare identity
  • == is used to compare equality

Example {#example}

First, create a list in Python.
首先,在Python中创建一个列表。

myListA = [1,2,3]

Next, create a copy of that list.
接下来,创建该列表的副本。

myListB = myListA

If we use the '' operator or the 'is' operator, both will result in a
如果我们使用&#39;
&#39;运算符或&#39;is&#39;运算符,两者都将导致a True output.
输出。

>>> myListA == myListB # both lists contains similar elements
True
>>> myListB is myListA # myListB contains the same elements
True

This is because both myListA and myListB are pointing to the same list variable, which I defined at beginning of my Python program. Both lists are exactly the same, both in identity and in content.
这是因为myListA和myListB都指向同一个列表变量,我在Python程序的开头定义了它。两个列表在身份和内容上完全相同。

However, what if I now create a new list?
但是,如果我现在创建一个新列表怎么办?

myListC = [1,2,3]

Performing the
表演== operator still shows that both lists are the same, in terms of content.
运算符仍然显示两个列表在内容方面是相同的。

>>> myListA == myListC
True

However, performing the
但是,表演了is operator will now produce a
运营商现在将生产一个False output. This is because myListA and myListC are two different variables, despite containing the same data. Even though they look the same, they are
输出。这是因为myListA和myListC是两个不同的变量,尽管包含相同的数据。即使它们看起来一样,它们也是如此 different .

>>> myListA is myListC
False # both lists have different reference

To sum up:
总结一下:

  • An is expression outputs True if both variables are pointing to the same reference
  • An == expression outputs True if both variables contain the same data

A Dictionary (a.k.a "dict") in python is a built-in datatype that can be used to store
python中的Dictionary(又名"dict")是一种可用于存储的内置数据类型 key-value pairs. This allows you to treat a
对。这可以让你治疗一个 dict like it's a
喜欢它是一个 database to store and organize data.
存储和组织数据。

The special thing about dictionaries is the way they are implemented. Hash-table-like structure makes it easy to check for existence - which means that we can easily determine if a specific key is present in the dictionary without needing to examine every element. The Python interpreter can just go to the location key and check if the key is there.
关于字典的特殊之处在于它们的实现方式。类似哈希表的结构使得检查存在变得容易 - 这意味着我们可以轻松确定字典中是否存在特定键,而无需检查每个元素。 Python解释器只需转到位置键并检查密钥是否存在。

Dictionaries can use almost any arbitrary datatypes, like strings, integers etc, for keys. However, values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as
字典几乎可以使用任意数据类型,如字符串,整数等,用于键。但是,不可清除的值,即包含列表,字典或其他可变类型(通过值而不是通过对象标识进行比较)的值可能不会用作键。用于键的数字类型遵循用于数字比较的常规规则:如果两个数字比较相等(例如1 and
1.0) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)
)然后它们可以互换使用来索引相同的字典条目。 (但请注意,由于计算机将浮点数存储为近似值,因此将它们用作字典键通常是不明智的。)

One most important requirement of a dictionary is that the keys
字典的一个最重要的要求是键 must be unique.
独一无二。
To create an empty dictionary just use a pair of braces:
要创建一个空字典,只需使用一对大括号:

    >>> teams = {}
    >>> type(teams)
    >>> <class 'dict'>

To create a non-empty dictionary with some initial values, place a comma-seperated list of key-value pairs:
要创建包含一些初始值的非空字典,请放置以逗号分隔的键值对列表:

    >>> teams = {'barcelona': 1875, 'chelsea': 1910}
    >>> teams
    {'barcelona': 1875, 'chelsea': 1910}

It's easy to add key-value pairs to an existing dictionary:
将键值对添加到现有字典很容易:

    >>> teams['santos'] = 1787
    >>> teams
    {'chelsea': 1910, 'barcelona': 1875, 'santos': 1787} # Notice the order - Dictionaries are unordered !
    >>> # extracting value - Just provide the key
    ...
    >>> teams['barcelona']
    1875

del operator is used to delete a key-value pair from the dict. In scenarios where a key that's already in use is again used to store values, the old value associated with that key is completely lost. Also, keep in mind that it's an error to extract the value using a non-existent key.
运算符用于从dict中删除键值对。在已经使用的密钥再次用于存储值的情况下,与该密钥关联的旧值完全丢失。另外,请记住,使用不存在的密钥提取值是错误的。

    >>> del teams['santos']
    >>> teams
    {'chelsea': 1910, 'barcelona': 1875}
    >>> teams['chelsea'] = 2017 # overwriting    
    >>> teams
    {'chelsea': 2017, 'barcelona': 1875}

in keyword can be used to check whether a key exist in the dict or not:
keyword可用于检查dict中是否存在密钥:

    >>> 'sanots' in teams
    False    
    >>> 'barcelona' in teams
    True
    >>> 'chelsea' not in teams
    False

keys is a built-in
是一个内置的 method that can be used to get the keys of a given dictionary. To extract the keys present in a dict as lists:
可以用来获取给定字典的键。要将dict中存在的键提取为列表:

    >>> club_names = list(teams.keys())    
    >>> club_names
    ['chelsea', 'barcelona']

Yet another way of creating a dictionary is using the
另一种创建字典的方法是使用 dict() method:
方法:

    >>> players = dict( [('messi','argentina'), ('ronaldo','portugal'), ('kaka','brazil')] ) # sequence of key-value pair is passed  
    >>> players
    {'ronaldo': 'portugal', 'kaka': 'brazil', 'messi': 'argentina'}
    >>> 
    >>> # If keys are simple strings, it's quite easier to specify pairs using keyword arguments
    ...
    >>> dict( totti = 38, zidane = 43 )
    {'zidane': 43, 'totti': 38}

Dict comprehensions can be used as well to create dictionaries from arbitrary key and value expressions:
也可以使用Dict理解来从任意键和值表达式创建字典:

    >>> {x: x**2 for x in (2, 4, 6)}
    {2: 4, 4: 16, 6: 36}

Looping in Dictionary
To simply loop over the keys in the dictionary, rather than the keys and values:
简单地循环遍历字典中的键,而不是键和值:

    >>> d = {'x': 1, 'y': 2, 'z': 3} 
    >>> for key in d:
    ...     print(key) # do something
    ...
    x
    y
    z

To loop over both key and value, you can use the following:
要循环键和值,可以使用以下内容:
For Python 2.x:
对于Python 2.x:

    >>> for key, item in d.iteritems():
    ...     print items
    ...
    1
    2
    3

Use
采用 items() for Python 3.x:
对于Python 3.x:

    >>> for key, item in d.items():
    ...     print(key, items)
    ...
    x 1
    y 2
    z 3

In Python, everything is an
在Python中,一切都是 object .

Objects represent a logical grouping of attributes. Attributes are data and/or functions. When an object is created in Python it is created with an
表示属性的逻辑分组。属性是数据和/或功能。当用Python创建一个对象时,它是用一个 identity ,
type , and
,和 value .

In other languages,
在其他语言中, primitives are
values that have no
没有 properties (attributes). For example, in javascript
(属性)。例如,在javascript中undefined,
null,
boolean,
string,
number, and
,和symbol (new in ECMAScript 2015) are primitives.
(ECMAScript 2015中的新内容)是原始的。

In Python, there are no primitives.
在Python中,没有原语。None,
booleans ,
strings ,
numbers , and even
, 乃至 functions are all
都是 objects regardless how they are created.
无论它们是如何创建的。

We can demonstrate this using some built-in functions:
我们可以使用一些内置函数来演示这一点:

Built-in constants
内置常量None,
True, and
,和False are
objects :

We test the
我们测试了None object here.
对象在这里。

>>> id(None)
4550218168
>>> type(None)
<class 'NoneType'>
>>> dir(None)
[__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> issubclass(type(None), object)
True

Next, let's inspect
接下来,让我们检查一下True.

>>> id(True)
4550117616
>>> type(True)
<class 'bool'>
>>> dir(True)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__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']
>>> issubclass(type(True), object)
True

No reason to leave out
没理由遗漏False!

>>> id(False)
4550117584
>>> type(False)
<class 'bool'>
>>> dir(False)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__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']
>>> issubclass(type(False), object)
True

Strings , even when created by a string literals, are also
即使是由字符串文字创建的,也是 objects .

>>> id("Hello campers!")
4570186864
>>> type('Hello campers!')
<class 'str'>
>>> dir("Hello campers!")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> issubclass(type('Hello campers!'), object)
True

Same with
与...相同 numbers.

>>> id(42)
4550495728
>>> type(42)
<class 'int'>
>>> dir(42)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__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']
>>> issubclass(type(42), object)
True

Functions are Objects Too {#functions-are-objects-too}

In Python, functions are first class objects.
在Python中,函数是第一类对象。

Functions in Python are also
在Python中也是 objects , created with an
,用。创建 identity ,
type , and
,和 value . They too can be passed into other
。他们也可以传递给其他人 functions :

>>> id(dir)
4568035688
>>> type(dir)
<class 'builtin_function_or_method'>
>>> dir(dir)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> issubclass(type(dir), object)
True

It is also possible to bind functions to a name and called the bound function using that name:
也可以将函数绑定到名称,并使用该名称调用绑定函数:

>>> a = dir
>>> print(a)
<built-in function dir>
>>> a(a)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

A tuple is a sequence of Python objects. Tuples are immutable which means they cannot be modified after creation, unlike lists.
元组是一系列Python对象。元组是不可变的,这意味着它们在创建后不能被修改,这与列表不同。

Creation:

An empty
一个空的tuple is created using a pair of round brackets,
是使用一对圆括号创建的,():

    >>> empty_tuple = ()
    >>> print(empty_tuple)
    ()
    >>> type(empty_tuple)
    <class 'tuple'>
    >>> len(empty_tuple)
    0

A
一种tuple with elements is created by separating the elements with commas (surrounding round brackets,
通过用逗号分隔元素来创建元素(围绕圆括号,(), are optional with exceptions):
,是例外的可选项):

    >>> tuple_1 = 1, 2, 3       # Create tuple without round brackets.
    >>> print(tuple_1)
    (1, 2, 3)
    >>> type(tuple_1)
    <class 'tuple'>
    >>> len(tuple_1)
    3
    >>> tuple_2 = (1, 2, 3)     # Create tuple with round brackets.
    >>> print(tuple_2)
    (1, 2, 3)
    >>> tuple_3 = 1, 2, 3,      # Trailing comma is optional.
    >>> print(tuple_3)
    (1, 2, 3)
    >>> tuple_4 = (1, 2, 3,)    # Trailing comma in round brackets is also optional.
    >>> print(tuple_4)
    (1, 2, 3)

A
一种tuple with a single element must have the trailing comma (with or without round brackets):
使用单个元素必须使用尾随逗号(带或不带圆括号):

    >>> not_tuple = (2)    # No trailing comma makes this not a tuple.
    >>> print(not_tuple)
    2
    >>> type(not_tuple)
    <class 'int'>
    >>> a_tuple = (2,)     # Single element tuple. Requires trailing comma.
    >>> print(a_tuple)
    (2,)
    >>> type(a_tuple)
    <class 'tuple'>
    >>> len(a_tuple)
    1
    >>> also_tuple = 2,    # Round brackets omitted. Requires trailing comma.
    >>> print(also_tuple)
    (2,)
    >>> type(also_tuple)
    <class 'tuple'>

Round brackets are required in cases of ambiguity (if the tuple is part of a larger expression):
在歧义的情况下需要圆括号(如果元组是更大表达式的一部分):

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity.
请注意,它实际上是一个逗号,它产生一个元组,而不是括号。括号是可选的,除了空元组情况,或者需要它们以避免语法歧义。

For example,
例如,f(a, b, c) is a function call with three arguments, while
是一个带有三个参数的函数调用,而f((a, b, c)) is a function call with a 3-tuple as the sole argument.
是一个函数调用,以3元组作为唯一参数。

    >>> print(1,2,3,4,)          # Calls print with 4 arguments: 1, 2, 3, and 4
    1 2 3 4
    >>> print((1,2,3,4,))        # Calls print with 1 argument: (1, 2, 3, 4,)
    (1, 2, 3, 4)
    >>> 1, 2, 3 == (1, 2, 3)     # Equivalent to 1, 2, (3 == (1, 2, 3))
    (1, 2, False)
    >>> (1, 2, 3) == (1, 2, 3)   # Use surrounding round brackets when ambiguous.
    True

A
一种tuple can also be created with the
也可以用。创建tuple constructor:
构造函数:

    >>> empty_tuple = tuple()
    >>> print(empty_tuple)
    ()
    >>> tuple_from_list = tuple([1,2,3,4])
    >>> print(tuple_from_list)
    (1, 2, 3, 4)
    >>> tuple_from_string = tuple("Hello campers!")
    >>> print(tuple_from_string)
    ('H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!')
    >>> a_tuple = 1, 2, 3
    >>> b_tuple = tuple(a_tuple)    # If the constructor is called with a tuple for
    the iterable,
    >>> a_tuple is b_tuple          # the tuple argument is returned.
    True

Accessing elements of a tuple:

Elements of
要点tuples are accessed and indexed the same way that
以相同的方式访问和索引lists are.
是。

    >>> my_tuple = 1, 2, 9, 16, 25
    >>> print(my_tuple)
    (1, 2, 9, 16, 25)

Zero indexed

    >>> my_tuple[0]
    1
    >>> my_tuple[1]
    2
    >>> my_tuple[2]
    9

Wrap around indexing

    >>> my_tuple[-1]
    25
    >>> my_tuple[-2]
    16

Packing and Unpacking:

The statement
该声明t = 12345, 54321, 'hello!' is an example of tuple packing: the values
是元组包装的一个例子:值12345,
54321and
'hello!' are packed together in a tuple. The reverse operation is also possible:
在元组中包装在一起。反向操作也是可能的:

    >>> x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
这足够恰当地称为序列解包,适用于右侧的任何序列。序列解包需要在等号的左侧有尽可能多的变量,因为序列中有元素。请注意,多重赋值实际上只是元组打包和序列解包的组合。

    >>> t = 1, 2, 3    # Tuple packing.
    >>> print(t)
    (1, 2, 3)
    >>> a, b, c = t    # Sequence unpacking.
    >>> print(a)
    1
    >>> print(b)
    2
    >>> print(c)
    3
    >>> d, e, f = 4, 5, 6    # Multiple assignment combines packing and unpacking.
    >>> print(d)
    4
    >>> print(e)
    5
    >>> print(f)
    6
    >>> a, b = 1, 2, 3       # Multiple assignment requires each variable (right)
    have a matching element (left).
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: too many values to unpack (expected 2)

Immutable:

tuples are immutable containers, guaranteeing
是不可变的容器,保证 which objects they contain will not change. It does
它们包含的对象不会改变。确实如此 not guarantee that the objects they contain will not change:
保证它们包含的对象不会改变:

    >>> a_list = []
    >>> a_tuple = (a_list,)    # A tuple (immutable) with a list (mutable) element.
    >>> print(a_tuple)
    ([],)

    >>> a_list.append("Hello campers!")
    >>> print(a_tuple)         # Element of the immutable is mutated.
    (['Hello campers!'],)

Uses:

Functions can only return a single value, however, a heterogenuous
函数只能返回单个值,但是,它是异质的tuple can be used to return multiple values from a function. One example is the built-in
可用于从函数返回多个值。一个例子是内置的enumerate function that returns an iterable of heterogenuous
返回异构的迭代函数tuples:

    >>> greeting = ["Hello", "campers!"]
    >>> enumerator = enumerate(greeting)
    >>> enumerator.next()
    >>> enumerator.__next__()
    (0, 'Hello')
    >>> enumerator.__next__()
    (1, 'campers!')

Decorators essentially work as wrappers. They modify the behaviour of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality, thus decorating it.
装饰器基本上用作包装器。它们在目标函数执行之前和之后修改代码的行为,而无需修改函数本身,增加原始功能,从而对其进行修饰。

Before going in detail about decorators, there are some concepts that should be clear. In Python, functions are objects and we can do a lot of useful stuff with them.
在详细介绍装饰器之前,有一些概念应该是清楚的。在Python中,函数是对象,我们可以用它们做很多有用的东西。

Assigning funtions to a variables: {#assigning-funtions-to-a-variables-}

def greet(name):
  return "Hello "+name
greet_someone = greet
print greet_someone("John")

Output: Hello John
输出:你好约翰

Run code

Defining functions inside other functions: {#defining-functions-inside-other-functions-}

def greet(name):
  def get_message():
    return "Hello "
  result = get_message()+name
  return result
print(greet("John"))

Output: Hello John
输出:你好约翰

Run code

Functions can also be passed as parameters to other functions: {#functions-can-also-be-passed-as-parameters-to-other-functions-}

def greet(name):
  return "Hello " + name
def call_func(func):
  other_name = "John"
  return func(other_name)  
print call_func(greet)

Output: Hello John
输出:你好约翰

Run code

Functions can return other functions: {#functions-can-return-other-functions-}

In other words, functions generating other functions.
换句话说,函数生成其他函数。

def compose_greet_func():
  def get_message():
    return "Hello there!"
  return get_message
greet = compose_greet_func()
print(greet())

Output: Hello there!
输出:你好!

Run code

Inner functions have access to the enclosing scope {#inner-functions-have-access-to-the-enclosing-scope}

More commonly known as a
通常称为aclosure. A very powerful pattern that we will come across while building decorators. Another thing to note, Python only allows
。我们在构建装饰器时会遇到的一个非常强大的模式。另外需要注意的是,Python只允许read access to the outer scope and not assignment. Notice how we modified the example above to read a "name" argument from the enclosing scope of the inner function and return the new function.
而不是分配。请注意我们如何修改上面的示例以从内部函数的封闭范围中读取"name"参数并返回新函数。

def compose_greet_func(name):
  def get_message():
      return "Hello there "+name+"!"
  return get_message
greet = compose_greet_func("John")
print(greet())

Output: Hello there John!
输出:你好约翰!

Run code

Composition of Decorators {#composition-of-decorators}

Function decorators are simply wrappers to existing functions. Putting the ideas mentioned above together, we can build a decorator. In this example let's consider a function that wraps the string output of another function by p tags.
函数装饰器只是现有函数的包装器。将上面提到的想法放在一起,我们可以建立一个装饰器。在这个例子中,让我们考虑一个用p标签包装另一个函数的字符串输出的函数。

def get_text(name):
   return "lorem ipsum, {0} dolor sit amet".format(name)

def p_decorate(func):
   def func_wrapper(name):
       return "`<p>`{0}`</p>`".format(func(name))
   return func_wrapper

my_get_text = p_decorate(get_text)
print (my_get_text("John"))

Output:
输出:<p>lorem ipsum, John dolor sit amet
lorem ipsum,John dolor坐下来</p>

Run code

That was our first decorator. A function that takes another function as an argument, generates a new function, augmenting the work of the original function, and returning the generated function so we can use it anywhere. To have
那是我们的第一个装饰师。将另一个函数作为参数的函数,生成一个新函数,扩充原始函数的工作,并返回生成的函数,以便我们可以在任何地方使用它。拥有get_text itself be decorated by
本身就是装饰的p_decorate, we just have to assign get
,我们只需要分配get text to the result of p decorate.
装饰。

get_text = p_decorate(get_text)
print (get_text("John"))

Output: lorem ipsum, John dolor sit amet
输出:lorem ipsum,John dolor坐下来

Another thing to notice is that our decorated function takes a name argument. All that we have to do in the decorator is to let the wrapper of get_text pass that argument.
另一件需要注意的事情是我们的装饰函数采用了名称参数。我们在装饰器中要做的就是让get_text的包装器传递该参数。

Python's Decorator Syntax {#python-s-decorator-syntax}

Python makes creating and using decorators a bit cleaner and nicer for the programmer through some
Python使程序员通过一些创建和使用装饰器更清洁,更好syntactic sugar. To decorate get
。装饰得到 text we don't have to get text = p
text = p decorator(get text). There is a neat shortcut for that, which is to mention the name of the decorating function before the function to be decorated. The name of the decorator should be perpended with an @ symbol.
文本)。有一个简洁的快捷方式,就是在要装饰的功能之前提到装饰功能的名称。装饰器的名称应该用@符号进行附加。

def p_decorate(func):
   def func_wrapper(name):
       return "`<p>`{0}`</p>`".format(func(name))
   return func_wrapper

@p_decorate
def get_text(name):
   return "lorem ipsum, {0} dolor sit amet".format(name)

print get_text("John")

Output:
输出:<p>lorem ipsum, John dolor sit amet
lorem ipsum,John dolor坐下来</p>

Run code

Now let's consider we wanted to decorate our get_text function by 2 other functions to wrap a div and strong tag around the string output.
现在让我们考虑我们想用2个其他函数来装饰我们的get_text函数,以在字符串输出周围包装div和strong标签。

def p_decorate(func):
   def func_wrapper(name):
       return "`<p>`{0}`</p>`".format(func(name))
   return func_wrapper

def strong_decorate(func):
    def func_wrapper(name):
        return "`<strong>`{0}`</strong>`".format(func(name))
    return func_wrapper

def div_decorate(func):
    def func_wrapper(name):
        return "`<div>`{0}`</div>`".format(func(name))
    return func_wrapper

With the basic approach, decorating get_text would be along the lines of
使用基本方法,装饰get_text将符合

get_text = div_decorate(p_decorate(strong_decorate(get_text)))

With Python's decorator syntax, the same thing can be achieved with much more expressive power.
使用Python的装饰器语法,可以通过更具表现力的功能实现同样的功能。

@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
   return "lorem ipsum, {0} dolor sit amet".format(name)

print (get_text("John"))

Output:
输出:<div><p><strong>lorem ipsum, John dolor sit amet
lorem ipsum,John dolor坐下来</strong></p></div>

Run code

One important thing to notice here is that the order of setting our decorators matters. If the order was different in the example above, the output would have been different.
这里要注意的一件重要事情是设置装饰器的顺序很重要。如果上面的示例中的顺序不同,则输出会有所不同。

Decorating Methods {#decorating-methods}

In Python, methods are functions that expect their first parameter to be a reference to the current object. We can build decorators for methods the same way, while taking self into consideration in the wrapper function.
在Python中,方法是期望其第一个参数是对当前对象的引用的函数。我们可以以相同的方式为方法构建装饰器,同时在包装器函数中考虑自我。

def p_decorate(func):
  def func_wrapper(self):
    return "`<p>`{0}`</p>`".format(func(self))
  return func_wrapper

class Person(object):
  def __init__(self):
    self.name = "John"
    self.family = "Doe"
  @p_decorate
  def get_fullname(self):
    return self.name+" "+self.family

my_person = Person()
print (my_person.get_fullname())

Output:
输出:<p>John Doe
约翰·多伊</p>

Run code

A much better approach would be to make our decorator useful for functions and methods alike. This can be done by putting
一个更好的方法是让我们的装饰器对函数和方法都很有用。这可以通过推杆来完成*args and **kwargs as parameters for the wrapper, then it can accept any arbitrary number of arguments and keyword arguments.
作为包装器的参数,它可以接受任意数量的参数和关键字参数。

def p_decorate(func):
   def func_wrapper(*args, **kwargs):
       return "`<p>`{0}`</p>`".format(func(*args, **kwargs))
   return func_wrapper

class Person(object):
    def __init__(self):
        self.name = "John"
        self.family = "Doe"
    @p_decorate
    def get_fullname(self):
        return self.name+" "+self.family

my_person = Person()
print (my_person.get_fullname())

Output :
输出:<p>John Doe
约翰·多伊</p>

Run code

Passing arguments to decorators {#passing-arguments-to-decorators}

Looking back at the example before the one above, you can notice how redundant the decorators in the example are. 3 decorators (divdecorate, pdecorate, strong_decorate) each with the same functionality, but wrapping the string with different tags.
回顾上面的示例之前的示例,您可以注意到示例中装饰器的冗余程度。 3个装饰器(divdecorate,pdecorate,strong_decorate),每个装饰器具有相同的功能,但用不同的标签包装字符串。

We can definitely do much better than that. Why not have a more general implementation for one that takes the tag to wrap with as a string? Yes please!
我们绝对可以做得更好。为什么没有一个更通用的实现,以使标记作为字符串包装?是的,请!

def tags(tag_name):
    def tags_decorator(func):
        def func_wrapper(name):
            return "<{0}>{1}</{0}>".format(tag_name, func(name))
        return func_wrapper
    return tags_decorator

@tags("p")
def get_text(name):
    return "Hello "+name

print (get_text("John"))

Output:
输出:<p>Hello John
你好约翰</p>

Run code

It took a bit more work in this case. Decorators expect to receive a function as an argument, that is why we will have to build a function that takes those extra arguments and generate our decorator on the fly. In the example above, tags is our decorator generator.
在这种情况下需要做更多的工作。装饰器期望接收函数作为参数,这就是为什么我们必须构建一个函数来获取那些额外的参数并动态生成装饰器。在上面的例子中,tags是我们的装饰生成器。

Debugging decorated functions {#debugging-decorated-functions}

At the end of the day, decorators are just wrapping our functions. In case of debugging, that can be problematic since the wrapper function does not carry the name, module and docstring of the original function. Based on the example above if we do:
在一天结束时,装饰者只是包装我们的功能。在调试的情况下,这可能是有问题的,因为包装器函数不携带原始函数的名称,模块和文档字符串。基于上面的例子,如果我们这样做:

print (get_text.__name__)

Output: func
输出:func wrapper. The output was expected to be get text yet, the attributes
文字,属性 name ,
doc , and
,和 module of get
获得 text got overridden by those of the wrapper(func wrapper.
包装。

Obviously we can re-set them within func_wrapper but Python provides a much nicer way.
显然我们可以在func_wrapper中重新设置它们,但Python提供了更好的方法。

Functools to the rescue

from functools import wraps
def tags(tag_name):
    def tags_decorator(func):
        @wraps(func)
        def func_wrapper(name):
            return "`<{0}>`{1}`</{0}>`".format(tag_name, func(name))
        return func_wrapper
    return tags_decorator

@tags("p")
def get_text(name):
    """returns some text"""
    return "Hello "+name

print (get_text.__name__) # get_text
print (get_text.__doc__) # returns some text
print (get_text.__module__) # __main__

Run code

You can notice from the output that the attributes of get_text are the correct ones now.
您可以从输出中注意到get_text的属性现在是正确的。

Python utilizes a for loop to iterate over a list of elements. This is unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value.
Python利用for循环迭代元素列表。这与C或Java不同,它使用for循环来逐步更改值并使用该值访问诸如数组之类的内容。

For loops iterate over collection-based data structures like lists, tuples, and dictionaries.
For循环遍历基于集合的数据结构,如列表,元组和字典。

The basic syntax is:
基本语法是:

for value in list_of_values:
  # use value inside this block

In general, you can use anything as the iterator value, where entries of the iterable can be assigned to. E.g. you can unpack tuples from a list of tuples:
通常,您可以使用任何内容作为迭代器值,其中可以为iterable的条目分配。例如,您可以从元组列表中解压缩元组:

list_of_tuples = [(1,2), (3,4)]

for a, b in list_of_tuples:
  print("a:", a, "b:", b)

On the other hand, you can loop over anything that is iterable. You can call a function or use a list literal.
另一方面,您可以遍历任何可迭代的东西。您可以调用函数或使用列表文字。

for person in load_persons():
  print("The name is:", person.name)

for character in ["P", "y", "t", "h", "o", "n"]:
  print("Give me a '{}'!".format(character))

Some ways in which For loops are used:
使用For循环的一些方法:

Iterate over the range() function

for i in range(10):
    print(i)

Rather than being a function, range is actually an immutable sequence type. The output will contain results from lower bound i.e 0 to the upper bound i.e 10, but excluding 10. By default the lower bound or the starting index is set to zero. Output:
范围实际上是一个不可变的序列类型,而不是一个函数。输出将包含来自下限的结果,即0到上限,即10,但不包括10.默认情况下,下限或起始索引设置为零。输出:

>
0
1
2
3
4
5
6
7
8
9
>

Additionally, one can specify the lower bound of the sequence and even the step of the sequence by adding a second and a third parameter.
另外,可以通过添加第二和第三参数来指定序列的下限甚至序列的步骤。

for i in range(4,10,2): #From 4 to 9 using a step of two
    print(i)

Output:
输出:

>
4
6
8
>

xrange() function

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object. It means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.
在大多数情况下,xrange和range在功能方面完全相同。它们都提供了一种生成整数列表供您使用的方法,但是请您随意使用。唯一的区别是range返回一个Python列表对象,xrange返回一个xrange对象。这意味着xrange实际上并不像运行时那样在运行时生成静态列表。它使用称为yielding的特殊技术根据需要创建值。该技术与一种称为生成器的对象一起使用。

One more thing to add. In Python 3.x, the xrange function does not exist anymore. The range function now does what xrange does in Python 2.x
还有一件事要补充。在Python 3.x中,xrange函数不再存在。范围函数现在执行xrange在Python 2.x中的功能

Iterate over values in a list or tuple

A = ["hello", 1, 65, "thank you", [2, 3]]
for value in A:
    print(value)

Output:
输出:

>
hello
1
65
thank you
[2, 3]
>

Iterate over keys in a dictionary (aka hashmap)

fruits_to_colors = {"apple": "#ff0000",
                    "lemon": "#ffff00",
                    "orange": "#ffa500"}

for key in fruits_to_colors:
    print(key, fruits_to_colors[key])

Output:
输出:

>
apple #ff0000
lemon #ffff00
orange #ffa500
>

Iterate over two lists of same size in a single loop with the zip() function

A = ["a", "b", "c"]
B = ["a", "d", "e"]

for a, b in zip(A, B):
  print a, b, a == b

Output:
输出:

>
a a True
b d False
c e False
>

Iterate over a list and get the corresponding index with the enumerate() function

A = ["this", "is", "something", "fun"]

for index,word in enumerate(A):
    print(index, word)

Output:
输出:

>
0 this
1 is
2 something
3 fun
>

A common use case is iterating over a dictionary:
一个常见的用例是迭代字典:

for name, phonenumber in contacts.items():
  print(name, "is reachable under", phonenumber)

If you absolutely need to access the current index of your iteration, do
如果您绝对需要访问迭代的当前索引,请执行 NOT use
采用range(len(iterable))! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function
!这是一个非常糟糕的做法,会让你从高级Python开发人员那里得到很多笑声。使用内置功能enumerate() instead:
代替:

for index, item in enumerate(shopping_basket):
  print("Item", index, "is a", item)

for/else statements Pyhton permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied. To use the else we have to make use of
Pyhton允许你在for循环中使用else,当循环体中没有条件满足时执行else case。要使用我们必须使用的其他break statement so that we can break out of the loop on a satisfied condition. If we do not break out then the else part will be executed.
声明,以便我们可以在满意的条件下突破循环。如果我们没有爆发,那么else部分将被执行。

week_days = ['Monday','Tuesday','Wednesday','Thursday','Friday']
today = 'Saturday'
for day in week_days:
  if day == today:
    print('today is a week day')
    break
else:
  print('today is not a week day')

In the above case the output will be
在上面的例子中,输出将是today is not a week day since the break within the loop will never be executed.
因为循环中的中断永远不会被执行。

Iterate over a list using inline loop function

We could also iterate inline using python. For example if we need to uppercase all the words in a list from a list, we could simply do the following:
我们也可以使用python迭代内联。例如,如果我们需要从列表中大写列表中的所有单词,我们可以简单地执行以下操作:

A = ["this", "is", "awesome", "shinning", "star"]

UPPERCASE = [word.upper() for word in A]
print (UPPERCASE)

Output:
输出:

>
['THIS', 'IS', 'AWESOME', 'SHINNING', 'STAR']

A function allows you to define a reusable block of code that can be executed many times within your program.
函数允许您定义可在程序中多次执行的可重用代码块。

Functions allow you to create more modular and
功能允许您创建更多模块化和DRY solutions to complex problems.
解决复杂问题。

While Python already provides many built-in functions such as
虽然Python已经提供了许多内置函数,例如print() and
len(), you can also define your own functions to use within your projects.
,您还可以定义自己的功能,以便在项目中使用。

One of the great advantages of using functions in your code is that it reduces the overall number of lines of code in your project.
在代码中使用函数的一大优势是它减少了项目中代码行的总数。

Syntax {#syntax}

In Python, a function definition has the following features:
在Python中,函数定义具有以下功能:

  1. The keyword
    关键字def

  2. a function name
    一个功能名称

  3. parentheses'()', and within parentheses input parameters, although the input parameters are optional.
    括号&#39;()&#39;,括号内的输入参数,尽管输入参数是可选的。

  4. a colon ':'
    冒号&#39;:&#39;

  5. some block of code to execute
    一些要执行的代码块

  6. a return statement (optional)
    一个return语句(可选)

a function with no parameters or returned values

def sayHello(): print("Hello!")
def sayHello():print("你好!")

sayHello() # calls the function, 'Hello!' is printed to the console
sayHello()#调用函数,&#39;你好!&#39;打印到控制台

a function with a parameter

def helloWithName(name): print("Hello " + name + "!")
def helloWithName(name):print("Hello"+ name +"!")

helloWithName("Ada") # calls the function, 'Hello Ada!' is printed to the console
helloWithName("Ada")#调用函数&#39;Hello Ada!&#39;打印到控制台

a function with multiple parameters with a return statement

def multiply(val1, val2): return val1 * val2
def multiply(val1,val2):返回val1 * val2

multiply(3, 5) # prints 15 to the console
乘以(3,5)#将15打印到控制台

Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegant code reuse without explicitly re-writing sections of code. This makes code more readable, easier to debug, and limits typing errors.
函数是代码块,只需调用函数即可重用。这样可以实现简单,优雅的代码重用,而无需显式重写代码段。这使代码更易读,更容易调试,并限制了输入错误。

Functions in Python are created using the
Python中的函数是使用def keyword, followed by a function name and function parameters inside parentheses.
关键字,后跟括号内的函数名和函数参数。

A function always returns a value. The
函数始终返回一个值。该return keyword is used by the function to return a value. If you don't want to return any value, the default value
函数使用关键字返回值。如果您不想返回任何值,则为默认值None will be returned.
将被退回。

The function name is used to call the function, passing the needed parameters inside parentheses.
函数名称用于调用函数,在括号内传递所需的参数。

# this is a basic sum function
def sum(a, b):
  return a + b

result = sum(1, 2)
# result = 3

You can define default values for the parameters, and that way Python will interpret that the value of that parameter is the default one if none is given.
您可以为参数定义默认值,这样Python将解释该参数的值是默认值,如果没有给出。

def sum(a, b=3):
  return a + b

result = sum(1)
# result = 4

You can pass the parameters in the order you want, using the name of the parameter.
您可以使用参数名称按所需顺序传递参数。

result = sum(b=2, a=2)
# result = 4

However, it is not possible to pass a keyword argument before a non-keyword one.
但是,无法在非关键字参数之前传递关键字参数。

result = sum(3, b=2)
#result = 5
result2 = sum(b=2, 3)
#Will raise SyntaxError

Functions are also Objects, so you can assign them to a variable, and use that variable like a function.
函数也是对象,因此您可以将它们分配给变量,并像函数一样使用该变量。

s = sum
result = s(1, 2)
# result = 3

Notes {#notes}

If a function definition includes parameters, you must provide the same number of parameters when you call the function.
如果函数定义包含参数,则在调用函数时必须提供相同数量的参数。

print(multiply(3))  # TypeError: multiply() takes exactly 2 arguments (0 given)

print(multiply('a', 5))  # 'aaaaa' printed to the console

print(multiply('a', 'b'))  # TypeError: Python can't multiply two strings

The block of code that the function will run includes all statements indented within the function.
函数将运行的代码块包括函数内缩进的所有语句。

def myFunc():
print('this will print')
print('so will this')

x = 7
# the assignment of x is not a part of the function since it is not indented

Variables defined within a function only exist within the scope of that function.
函数中定义的变量仅存在于该函数的范围内。

def double(num):
x = num * 2
return x

print(x)  # error - x is not defined
print(double(4))  # prints 8

Python interprets the function block only when the function is called and not when the function is defined. So even if the function definition block contains some sort of error, the python interpreter will point that out only when the function is called.
Python仅在调用函数时解释函数块,而不是在定义函数时解释。因此,即使函数定义块包含某种错误,python解释器也只会在调用函数时指出它。

Generators are a special type of function that allows you to return values without ending a function. It does this by using the
生成器是一种特殊类型的函数,它允许您在不结束函数的情况下返回值。它通过使用yield keyword. Similar to
关键词。如同return, the
yield expression will return a value to the caller. The key difference between the two is that
表达式将向调用者返回一个值。两者之间的关键区别在于yield will suspend the function, allowing for more values to be returned in the future.
将暂停该功能,允许将来返回更多值。

Generators are iterable so they can be used cleanly with for loops or anything else that iterates.
生成器是可迭代的,因此它们可以与for循环或任何其他迭代一起使用。

def my_generator():
    yield 'hello'
    yield 'world'
    yield '!'

for item in my_generator():
    print(item)

# output:
# hello
# world
# !

Like other iterators, generators can be passed to the
像其他迭代器一样,生成器可以传递给next function to retrieve the next item. When a generator has no more values to yield, a
函数检索下一个项目。当生成器没有更多的值可以产生时,aStopIteration error is raised.
提出错误。

g = my_generator()
print(next(g))
# 'hello'
print(next(g))
# 'world'
print(next(g))
# '!'
print(next(g))
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# StopIteration

Generators are particularly useful when you need to create a large set of values but do not need to keep them all in memory at the same time. For example, if you need to print the first million fibonacci numbers, you would typically return a list of a million values and iterate over the list to print each value. However with a generator, you can return each value one at a time:
当您需要创建大量值但不需要将它们全部保存在内存中时,生成器特别有用。例如,如果您需要打印第一百万个斐波那契数字,通常会返回一百万个值的列表并迭代列表以打印每个值。但是使用生成器,您可以一次返回一个值:

def fib(n):
    a = 1
    b = 1
    for i in range(n):
        yield a
        a, b = b, a + b

for x in fib(1000000):
    print(x)

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration.
Python支持迭代容器的概念。这是使用两种不同的方法实现的;这些用于允许用户定义的类支持迭代。

Python Docs - Iterator Types

Iteration is the process of programmatically repeating a step a given number of times. A programmer can make use of iteration to perform the same operation on every item in a collection of data, for example printing out every item in a list.
迭代是以编程方式重复步骤给定次数的过程。程序员可以利用迭代对数据集合中的每个项目执行相同的操作,例如打印出列表中的每个项目。

  • Objects can implement a __iter__() method that returns an iterator object to support iteration.

Iterator objects must implement:
迭代器对象必须实现:

  • __iter__(): returns the iterator object.
  • __next__(): returns the next object of the container.iterator object = 'abc'. iter () print(iterator object) print(id(iterator object)) print(id(iterator object. iter ())) # Returns the iterator itself. print(iterator object. next ()) # Returns 1st object and advances iterator. print(iterator object. next ()) # Returns 2nd object and advances iterator. print(iterator object. next ()) # Returns 3rd object and advances iterator. print(iterator object. next ()) # Raises StopIteration Exception.

Output :
输出:

<str_iterator object at 0x102e196a0>
4343305888
4343305888
a
b
c
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-1-d466eea8c1b0> in <module>()
      6 print(iterator_object.__next__())     # Returns 2nd object and advances iterator.
      7 print(iterator_object.__next__())     # Returns 3rd object and advances iterator.
----> 8 print(iterator_object.__next__())     # Raises StopIteration Exception.

StopIteration:

Ternary operations in Python, often also referred to as conditional expressions, allow the programmer to perform an evaluation and return a value based on the truth of the given condition.
Python中的三元操作(通常也称为条件表达式)允许程序员执行评估并根据给定条件的真实性返回值。

The ternary operator differs from a standard
三元运算符与标准不同if,
else,
elif structure in the sense that it is not a control flow structure, and behaves more like other operators such as
结构在某种意义上说它不是一个控制流结构,而且表现得更像其他运算符== or
要么!= in the Python language.
在Python语言中。

Example {#example-1}

In this example, the string
在这个例子中,字符串Even is returned if the
如果是,则返回val variable is even, otherwise the string
变量是偶数,否则是字符串Odd is returned. The returned string is then assigned to the
退回。然后将返回的字符串分配给is_even variable and printed to the console.
变量并打印到控制台。

Input {#input}

for val in range(1, 11):
    is_even = "Even" if val % 2 == 0 else "Odd"
    print(val, is_even, sep=' = ')

Output {#output}

1 = Odd
2 = Even
3 = Odd
4 = Even
5 = Odd
6 = Even
7 = Odd
8 = Even
9 = Odd
10 = Even

Python utilizes the
Python利用了while loop similarly to other popular languages. The
循环类似于其他流行语言。该while loop evaluates a condition then executes a block of code if the condition is true. The block of code executes repeatedly until the condition becomes false.
如果条件为真,循环计算条件然后执行代码块。代码块重复执行,直到条件变为false。

The basic syntax is:
基本语法是:

counter = 0
while counter < 10:
   # Execute the block of code here as
   # long as counter is less than 10

An example is shown below:
一个例子如下所示:

days = 0    
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
while days < 7:
   print("Today is " + week[days])
   days += 1

Output:
输出:

Today is Monday
Today is Tuesday
Today is Wednesday
Today is Thursday
Today is Friday
Today is Saturday
Today is Sunday

Line-by-Line explanation of the above CODE:
以上CODE的逐行说明:

  1. the variable 'days' is set to a value 0.
  2. a variable week is assigned to a list containing all the days of the week.
  3. while loop starts
  4. the block of code will be executed until the condition returns 'true'.
  5. the condition is 'days<7' which roughly says run the while loop until the point the variable days is less than 7
  6. So when the days=7 the while loop stops executing.
  7. the days variable gets updated on every iteration.
  8. When the while loop runs for the first time, the line 'Today is Monday' is printed onto the console and the variable days becomes equal to 1.
  9. Since the variable days is equal to 1 which is less than 7, the while loop is executed again.
  10. It goes on again and again and when the console prints 'Today is Sunday' the variable days is now equal to 7 and the while loop stops executing.

You can download Python from this official
你可以从这个官方下载Pythonlink. Based on your OS (Windows or Linux or OSX), you might want to install Python 3 following
。根据您的操作系统(Windows或Linux或OSX),您可能希望安装Python 3these instructions.

Using Virtual Environments {#using-virtual-environments}

It is always a great idea to
这总是一个好主意sandbox your Python installation and keep it separate from your
您的Python安装并将其与您的安装分开 System Python . The
。该 System Python is the path to Python interpreter, which is used by other modules installed along with your OS.
是Python解释器的路径,它与您的操作系统一起安装的其他模块一起使用。

It's
它的 not safe to install Python Web-frameworks or libraries directly using
直接使用安装Python Web框架或库 System Python . Instead, you can use
。相反,你可以使用Virtualenv to create and spawn a separate Python process when you are developing Python applications.
在开发Python应用程序时创建和生成单独的Python进程。

Virtualenvwrapper {#virtualenvwrapper}

The
Virtualenvwrapper module makes it easy for you to manage and sandbox multiple Python sandboxed environments in one machine, without corrupting any modules or services written in Python and used by your machine.
使您可以轻松地在一台计算机上管理和沙箱化多个Python沙盒环境,而不会破坏用Python编写并由您的计算机使用的任何模块或服务。

Of course, most cloud hosted development environments such as
当然,大多数云托管开发环境如Nitrous or
要么Cloud9 also come with these pre-installed and ready for you to get coding! You can quickly pick a box from your dashboard and start coding after activating a Python 3 environment.
还附带这些预安装并准备好让您获得编码!您可以从仪表板中快速选择一个框,并在激活Python 3环境后开始编码。

In
Cloud9, you need to select the Django box while creating a new development environment.
,您需要在创建新的开发环境时选择Django框。

A few shell command examples follow. If you wish to copy-paste, do note that the
下面是一些shell命令示例。如果你想复制粘贴,请注意$ sign is a shorthand for the terminal prompt, it's not part of the command. My terminal prompt looks something like this:
sign是终端提示的简写,它不是命令的一部分。我的终端提示符如下所示:

alayek:~/workspace (master) $

And, an
ls would look like
看起来像

alayek:~/workspace (master) $ ls

But, while writing the same in this documentation, I would be writing it as
但是,在本文档中编写相同的内容时,我会将其编写为

$ ls

Getting back to our discussion, you can create a Python 3 interpreter-included sandbox on Cloud9 by running on your cloud terminal:
回到我们的讨论,您可以通过在云终端上运行在Cloud9上创建包含Python 3解释器的沙箱:

$ mkvirtualenv py3 --python=/usr/bin/python3

You have to run it only once after creating a new box for your project. Once executed, this command would create a new sandboxed virtualenv ready for you to use, named
在为项目创建新框后,您只需运行一次。一旦执行,该命令将创建一个新的沙盒virtualenv,供您使用,命名py3.

To view available virtual environments, you can use
要查看可用的虚拟环境,您可以使用

$ workon

To activate
激活py3, you can use the
,你可以使用workon command with the name of the environment:
带有环境名称的命令:

$ workon py3

All three terminal commands above would also work on local Linux machines or OSX machines. These are
上面的所有三个终端命令也适用于本地Linux机器或OSX机器。这些是virtualenvwrapper commands; so if you are planning on using them, make sure you have this module installed and added to
命令;因此,如果您计划使用它们,请确保已安装并添加此模块PATH variable.
变量。

If you are inside a virtual environment; you can easily find that out by checking your terminal prompt. The environment name will be clearly shown in your terminal prompt.
如果你在虚拟环境中;您可以通过检查终端提示轻松找到它。环境名称将在终端提示中清晰显示。

For instance, when I am inside the
例如,当我在里面的时候py3 environment, I will be seeing this as my terminal prompt:
环境,我将看到这作为我的终端提示:

(py3)alayek:~/workspace (master) $

Notice the
请注意(py3) in braces! If for some reason you are not seeing this, even if you are inside a virtual env; you can try doing one of the things
在括号!如果由于某种原因你没有看到这个,即使你在虚拟的环境中;你可以尝试做其中的一件事mentioned here.

To get out of a virtual environment or to deactivate one - use this command:
要退出虚拟环境或停用虚拟环境 - 请使用以下命令:

$ deactivate

Again, this works only with virtualenvwrapper module.
同样,这仅适用于virtualenvwrapper模块。

Pipenv {#pipenv}

An alternative to using virtualenvwrapper is
使用virtualenvwrapper的另一种方法是Pipenv. It automatically creates virtual environments for your projects, and maintains a
。它会自动为您的项目创建虚拟环境,并维护一个Pipfile which contains the dependencies. Using Pipenv means you no longer need to use pip and virtualenv separately, or manage your own
其中包含依赖项。使用Pipenv意味着您不再需要单独使用pip和virtualenv,或管理自己的requirements.txt file. For those familiar with JavaScript, Pipenv is similar to using a packaging tool like
文件。对于那些熟悉JavaScript的人来说,Pipenv类似于使用类似的包装工具npm.

To get started with Pipenv, you can follow this very detailed
要开始使用Pipenv,您可以按照这个非常详细的方式进行操作guide. Pipenv makes it easy to
。皮彭夫很容易specify which version of Python you wish to use for each project,
你希望用于每个项目,import from an existing
来自现有的requirements.txt file and
文件和graph your dependencies.
你的依赖。

中英文模式阅读
中文模式阅读
英文模式阅读

查看英文原文

查看更多文章

公众号:银河系1号
公众号:银河系1号

联系邮箱:public@space-explore.com
联系邮箱:public@space-explore.com

(未经同意,请勿转载)
(未经同意,请勿转载)