Some of the special uses in Python

Source: Internet
Author: User

1. Some special methods

__init__ (self,...)

This method is called before the new object is returned to use.

__del__ (self)

Called exactly before the object is to be deleted.

__str__ (self)

Called when we use the PRINT statement on an object or use STR ().

__lt__ (Self,other)

Called when the less-than operator (<) is used. Similarly, there are special methods for all operators (+,>, and so on).

__getitem__ (Self,key)

Called when using the X[key] index operator.

__len__ (self) is called when using the built-in Len () function on a Sequence object.

2. Comprehensive list

With list synthesis, 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 twice times the original. For this kind of application, list synthesis is the most ideal method.

Use list synthesis:

#!/usr/bin/python

# Filename:list_comprehension.py

Listone = [2,3,4]

Listtwo = [2*i for i in Listone if I>2]

Print Listtwo

[email protected] code]# python list_comprehension.py

[6, 8]

A new list is exported by specifying an action (2*i) to satisfy the number of conditions (if I > 2). Note that the original list has not changed. In many cases, we use loops to work with every element of the list, and using list synthesis can do the same thing in a more precise, concise, and clear way.

3. Accept tuples and lists in functions

When you want a function to receive a tuple or dictionary-like parameter, there is a special way to use the * and * * prefixes, respectively. This method is particularly useful when a function needs to obtain a variable number of arguments.

#!/usr/bin/python

# Filename:args.py

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

[[email protected] code]# python

Python 2.4.3 (#1, Dec 10 2010, 17:24:32)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2

Type "Help", "copyright", "credits" or "license" for more information.

>>> 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

...

>>> Powersum (2,3,4)

25

>>> Powersum (2,10)

100

>>>

Because there is a * prefix before the args variable, all the extra function arguments are stored as a tuple in args. If you are using a * * prefix, the extra arguments are considered to be a dictionary key/value pair.

4, LAMPDA

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

#!/usr/bin/python

# Filename:lambda.py

def make_repeater (n):

Return Lambda S:s*n

twice = Make_repeater (2)

Print twice (' word ')

Print twice (5)

[email protected] code]# python lambda.py

Wordword

10

Use the Make_repeater function to create a new function object at run time and return it. A lambda statement is used to create a function object. Essentially, a lambda requires a parameter, followed only by a single expression as the body of the function, and the value of the expression is returned by the new function. Note that even the print statement cannot be used in lambda form, only expressions are used.

5. Exec and eval statements

The EXEC statement is used to execute a python statement stored in a string or file. For example, we can generate a string that contains Python code at run time, and then execute the statements using the EXEC statement.

[[email protected] code]# python

Python 2.4.3 (#1, Dec 10 2010, 17:24:32)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2

Type "Help", "copyright", "credits" or "license" for more information.

>>> exec ' print ' Hello world '

Hello World

The eval statement is used to calculate a valid python expression stored in a string.

>>> eval (' 2*4 ')

8

>>>

6. Assert statement

Used to declare a condition to be true. For example, if you are very confident that there is at least one element in the list you are using, and you want to test this and throw an error when it is not true, then the Assert statement is the ideal statement to apply in this case. When an Assert statement fails, a assertionerror is raised.

>>> mylist = [' Item ']

>>> assert Len (mylist) >= 1

>>> Mylist.pop ()

' Item '

>>> assert Len (mylist) >= 1

Traceback (most recent):

File "<stdin>", line 1, in?

Assertionerror

6. repr function

The REPR function is used to obtain the canonical string representation of an object. The inverse quotation marks (also known as converters) can accomplish the same function. Note that most of the time there is an eval (repr (object)) = = object.

>>> i = []

>>> i.append (' item ')

>>> I

[' Item ']

>>> ' I '

"[' Item ']"

>>> repr (i)

"[' Item ']"

>>>

Basically, the repr function and the inverse quotation mark are used to get the printable representation of an object that is always there. You can control what your object returns when it is called by the REPR function by defining the __repr__ method of the class.

Some of the special uses in Python

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.