search
HomeBackend DevelopmentPython Tutorial17 Python tricks and tricks to share
17 Python tricks and tricks to shareMar 19, 2017 pm 02:40 PM
python

Showing a limited interface to the outside

When publishing a python third-party package, it is not expected that all ## in the code #Function or class can be imported externally, add all attribute in init.py, and fill in the list The imported class or function name can limit the import and prevent external import of other functions or classes.

17 Python tricks and tricks to share

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from base import APIBase
from client import Client
from decorator import interface, export, stream
from server import Server
from storage import Storage
from util import (LogFormatter, disable_logging_to_stderr,
                       enable_logging_to_kids, info)
all = ['APIBase', 'Client', 'LogFormatter', 'Server',
           'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids',
           'export', 'info', 'interface', 'stream']
The magic of with

The with statement requires an

object that supports the context management protocol , context management protocol Contains two methods, enter and exit. The with statement establishes the runtime context and needs to perform entry and exit operations through these two methods.

Where

ContextExpression is the expression following with, which returns a context management object.

# 常见with使用场景
with open("test.txt", "r") as my_file:  # 注意, 是enter()方法的返回值赋值给了my_file,
    for line in my_file:
        print line
For detailed principles, you can view this article, a brief discussion of Python’s with statement.

Knowing the specific principles, we can customize a class that supports the context management protocol, and implement the enter and exit methods in the class.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MyWith(object):
    def init(self):
        print "init method"
    def enter(self):
        print "enter method"
        return self  # 返回对象给as后的变量
    def exit(self, exc_type, exc_value, exc_traceback):
        print "exit method"
        if exc_traceback is None:
            print "Exited without Exception"
            return True
        else:
            print "Exited with Exception"
            return False
def test_with():
    with MyWith() as my_with:
        print "running my_with"
    print "------分割线-----"
    with MyWith() as my_with:
        print "running before Exception"
        raise Exception
        print "running after Exception"
if name == 'main':
    test_with()
The execution results are as follows:

init method
enter method
running my_with
exit method
Exited without Exception
------分割线-----
init method
enter method
running before Exception
exit method
Exited with Exception
Traceback (most recent call last):
  File "bin/python", line 34, in <module>
    exec(compile(filef.read(), file, "exec"))
  File "test_with.py", line 33, in <module>
    test_with()
  File "test_with.py", line 28, in test_with
    raise Exception
Exception</module></module>
It is proved that the enter method will be executed first, then the logic in with will be called, and finally exit will be executed for exit processing, and even if an exception occurs, it can Normal exit

Usage of filter

Compared with filter,

map and reduce will be used more frequently. Filter is just like its name, according to certain rules Filter Remove some elements.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
lst = [1, 2, 3, 4, 5, 6]
# 所有奇数都会返回True, 偶数会返回False被过滤掉
print filter(lambda x: x % 2 != 0, lst)
#输出结果
[1, 3, 5]
Judgment in one line

When the condition is met, the variable after the equal sign is returned, otherwise the statement after else is returned.

lst = [1, 2, 3]
new_lst = lst[0] if lst is not None else None
print new_lst
# 打印结果
1
Single case of decorator

Use decorator to implement simple

single case mode

# 单例装饰器
def singleton(cls):
    instances = dict()  # 初始为空
    def _singleton(*args, **kwargs):
        if cls not in instances:  #如果不存在, 则创建并放入字典
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return _singleton
@singleton
class Test(object):
    pass
if name == 'main':
    t1 = Test()
    t2 = Test()
    # 两者具有相同的地址
    print t1, t2

static method decorator

Two commonly used decorations in classes, first distinguish them:

  • Ordinary member function, the first implicit parameter is

    Object

  • classmethod decorator, class method (it feels very similar to the class method in OC), the first one is implicit The parameter is class

  • staticmethod decorator, without any implicit parameters. static in python The method is similar to the static method in C++

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    class A(object):
        # 普通成员函数
        def foo(self, x):
            print "executing foo(%s, %s)" % (self, x)
        @classmethod   # 使用classmethod进行装饰
        def class_foo(cls, x):
            print "executing class_foo(%s, %s)" % (cls, x)
        @staticmethod  # 使用staticmethod进行装饰
        def static_foo(x):
            print "executing static_foo(%s)" % x
    def test_three_method():
        obj = A()
        # 直接调用噗通的成员方法
        obj.foo("para")  # 此处obj对象作为成员函数的隐式参数, 就是self
        obj.class_foo("para")  # 此处类作为隐式参数被传入, 就是cls
        A.class_foo("para")  #更直接的类方法调用
        obj.static_foo("para")  # 静态方法并没有任何隐式参数, 但是要通过对象或者类进行调用
        A.static_foo("para")
    if name == 'main':
        test_three_method()
    
    # 函数输出
    executing foo(<main.a>, para)
    executing class_foo(<class>, para)
    executing class_foo(<class>, para)
    executing static_foo(para)
    executing static_foo(para)</class></class></main.a>
  • property decorator

    Define private class properties
  • Combine property with decorator to realize property privatization (
simpler

safe implementation of get and set methods).

#python内建函数
property(fget=None, fset=None, fdel=None, doc=None)
fget is the function that gets the value of the attribute, fset is the function that sets the attribute value, fdel is the function that

deletes the

attribute, doc is a string (like Comments are the same). From an implementation perspective, these parameters are optional. property has three methods getter(), setter() and

delete

() to specify fget, fset and fdel. This means the following line:

class Student(object):
    @property  #相当于property.getter(score) 或者property(score)
    def score(self):
        return self._score
    @score.setter #相当于score = property.setter(score)
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value  100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
iter magic

    By combining yield and iter, we can turn an object into an iterable
  • By rewriting str, you can directly print the object in the desired form
  • #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    class TestIter(object):
        def init(self):
            self.lst = [1, 2, 3, 4, 5]
        def read(self):
            for ele in xrange(len(self.lst)):
                yield ele
        def iter(self):
            return self.read()
        def str(self):
            return ','.join(map(str, self.lst))
    
        repr = str
    def test_iter():
        obj = TestIter()
        for num in obj:
            print num
        print obj
    if name == 'main':
        test_iter()
  • Magical partial

partial is very similar to imitation in C++ function (function object).

In stack

overflow

, a running method similar to partial is given:

def partial(func, *part_args):
    def wrapper(*extra_args):
        args = list(part_args)
        args.extend(extra_args)
        return func(*args)
    return wrapper
Use the

closure

feature binding to pre-bind some Function parameters, returns a callable variable until the actual call is executed:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import partial
def sum(a, b):
    return a + b
def test_partial():
    fun = partial(sum, 2)   # 事先绑定一个参数, fun成为一个只需要一个参数的可调用变量
    print fun(3)  # 实现执行的即是sum(2, 3)
if name == 'main':
    test_partial()

# 执行结果
5

神秘eval

eval我理解为一种内嵌的python解释器(这种解释可能会有偏差), 会解释字符串为对应的代码并执行, 并且将执行结果返回。

看一下下面这个例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
    return 3
def test_second(num):
    return num
action = {  # 可以看做是一个sandbox
        "para": 5,
        "test_first" : test_first,
        "test_second": test_second
        }
def test_eavl():  
    condition = "para == 5 and test_second(test_first) > 5"
    res = eval(condition, action)  # 解释condition并根据action对应的动作执行
    print res
if name == '_

exec

>’, mode)编译字节码。 mode的取值为exec和eval

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
    print "hello"
def test_second():
    test_first()
    print "second"
def test_third():
    print "third"
action = {
        "test_second": test_second,
        "test_third": test_third
        }
def test_exec():
    exec "test_second" in action
if name == 'main':
    test_exec()  # 无法看到执行结果

getattr

getattr(object, name[, default])返回对象的命名属性,属性名必须是字符串。如果字符串是对象的属性名之一,结果就是该属性的值。例如, getattr(x, ‘foobar’) 等价于 x.foobar。 如果属性名不存在,如果有默认值则返回默认值,否则触发 AttributeError 。

# 使用范例
class TestGetAttr(object):
    test = "test attribute"
    def say(self):
        print "test method"
def test_getattr():
    my_test = TestGetAttr()
    try:
        print getattr(my_test, "test")
    except AttributeError:
        print "Attribute Error!"
    try:
        getattr(my_test, "say")()
    except AttributeError: # 没有该属性, 且没有指定返回值的情况下
        print "Method Error!"
if name == 'main':
    test_getattr()

# 输出结果
test attribute
test method

命令行处理

def process_command_line(argv):
    """
    Return a 2-tuple: (settings object, args list).
    `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
    """
    if argv is None:
        argv = sys.argv[1:]
    # initialize the parser object:
    parser = optparse.OptionParser(
        formatter=optparse.TitledHelpFormatter(width=78),
        add_help_option=None)
    # define options here:
    parser.add_option(      # customized description; put --help last
        '-h', '--help', action='help',
        help='Show this help message and exit.')
    settings, args = parser.parse_args(argv)
    # check number of arguments, verify values, etc.:
    if args:
        parser.error('program takes no command-line arguments; '
                     '"%s" ignored.' % (args,))
    # further process settings & args if necessary
    return settings, args
def main(argv=None):
    settings, args = process_command_line(argv)
    # application code here, like:
    # run(settings, args)
    return 0        # success
if name == 'main':
    status = main()
    sys.exit(status)

读写csv文件

# 从csv中读取文件, 基本和传统文件读取类似
import csv
with open('data.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row
# 向csv文件写入
import csv
with open( 'data.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(['name', 'address', 'age'])  # 单行写入
    data = [
            ( 'xiaoming ','china','10'),
            ( 'Lily', 'USA', '12')]
    writer.writerows(data)  # 多行写入

各种时间形式转换

只发一张网上的图, 然后查文档就好了, 这个是记不住的

17 Python tricks and tricks to share

字符串格式化

一个非常好用, 很多人又不知道的功能:

>>> name = "andrew"
>>> "my name is {name}".format(name=name)
'my name is andrew'

The above is the detailed content of 17 Python tricks and tricks to share. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools