Python Study Notes (11): More

Source: Internet
Author: User
1. Special Methods

Some special methods in the class have special meanings, such as the _ init _ and _ del _ methods. Generally, special methods are used to simulate a behavior. If you want to use index operations like x [Key] for your class, you only need to implement the _ getitem _ () method.

Name Description
_ Init _ (self ,...) This method is called just before the newly created object is returned for use.
_ Del _ (Self) It is called just before the object is deleted.
_ STR _ (Self) It is called when we use the print statement for an object or STR.
_ LT _ (self, other) It is called when the operator is smaller than (<. Similarly, all operators (+,>, and so on) have special methods.
_ Getitem _ (self, key) It is called when the X [Key] index operator is used.
_ Len _ (Self) Call a sequence object when using the built-in Len () function.
2. Single statement Block

Generally, each statement block is separated from other statement blocks by its indentation level. However, sometimes your statement block contains only one statement, you can specify it in the same row of the Condition Statement or loop statement.

flag = Trueif flag: print("Yes")

Although this can make your program smaller, I strongly recommend that you do not use this scaling method in addition to Testing errors. One of the main reasons not to use it is that once you use the appropriate indentation, you can easily add an additional statement.

3. Comprehensive List

You can export a new list from an existing list. For example, you have a list of numbers, and you want to get a corresponding list, so that all the numbers greater than 2 are two times the original number. For such applications, list synthesis is the most ideal method.

listone = [2, 3, 4]listtwo = [2 * i for i in listone if i > 2]print(listtwo)

In this section, all the numbers greater than 2 in listone are multiplied by 2 to obtain a new listtwo. Running result:

[6, 8]

4. Receiving tuples and lists in Functions

When you want a function to receive parameters in the form of tuples or dictionaries, there is a special method that uses the * and * prefixes respectively. This method is particularly useful when the function needs to obtain variable numbers of parameters.

def powersum(power, *args):    '''Return the sum of each argument raised to specified power.'''    total = 0    for i in args:        total += pow(i, power)    return total

Because there is a * prefix before The args variable, all redundant function parameters are stored as a tuple in args. If the prefix is **, redundant parameters are considered as Dictionary key/value pairs.

5. Lambda form

Lambda statements are used to create new function objects and return them at runtime.

def make_repeater(n):    return lambda s : s * ntwice = make_repeater(2)print(twice("ha"))print(twice(5))

Running result:

Haha

10

Here, we use the make_repeater function to create a new function object at runtime and return it. Lambda statements are used to create function objects. Essentially, Lambda requires a parameter, followed by a single expression as the function body, and the value of the expression is returned by the newly created function. Note that even print statements cannot be used in the lambda format, but expressions are only allowed.

6. exec and eval statements

Exec statements are used to execute Python statements stored in strings or files. For example, we can generate a string containing Python code at runtime, and then execute these statements using exec statements.

exec("print('Hello World')")

Running result:

Hello World

The eval statement is used to calculate the valid Python expression stored in the string.

eval("2 * 3")

Running result:

6

7. Assert statement

The assert statement is used to declare that a condition is true. For example, if you are very sure that a list you are using has at least one element, and you want to test this and cause an error when it is not true, the assert statement is an ideal statement applied in this case. When the assert statement fails, an assertionerror is thrown.

>>> mylist = ["item"]>>> assert(len(mylist) >= 1)>>> mylist.pop()'item'>>> assert(len(mylist) >= 1)Traceback (most recent call last):  File "<pyshell#13>", line 1, in <module>    assert(len(mylist) >= 1)AssertionError
8. Repr Function

The repr function is used to obtain the standard string representation of an object. Note: In most cases, Eval (Repr (object) = object.

>>> i = []>>> i.append("item")>>> repr(i)"['item']"

Basically, the Repr function and backquotes are used to obtain the printable representation of an object. You can define the _ repr _ method of the class to control the content returned when your object is called by the Repr function.

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.