一波神奇的Python语句、函数与方法的使用技巧总结
显示有限的接口到外部
当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init__.py中添加__all__属性,该list中填写可以import的类或者函数名, 可以起到限制的import的作用, 防止外部import其他函数或者类。
#!/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']
with的魔力
with语句需要支持上下文管理协议的对象, 上下文管理协议包含__enter__和__exit__两个方法。 with语句建立运行时上下文需要通过这两个方法执行进入和退出操作。
其中上下文表达式是跟在with之后的表达式, 该表达式返回一个上下文管理对象。
# 常见with使用场景 with open("test.txt", "r") as my_file: # 注意, 是__enter__()方法的返回值赋值给了my_file, for line in my_file: print line
知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__enter__和__exit__方法。
#!/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()
执行结果如下:
__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(__file__f.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
证明了会先执行__enter__方法, 然后调用with内的逻辑, 最后执行__exit__做退出处理, 并且, 即使出现异常也能正常退出
filter的用法
相对filter而言, map和reduce使用的会更频繁一些, filter正如其名字, 按照某种规则过滤掉一些元素。
#!/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]
一行作判断
当条件满足时, 返回的为等号后面的变量, 否则返回else后语句。
lst = [1, 2, 3] new_lst = lst[0] if lst is not None else None print new_lst # 打印结果 1
装饰器之单例
使用装饰器实现简单的单例模式
# 单例装饰器 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
staticmethod装饰器
类中两种常用的装饰, 首先区分一下他们:
普通成员函数, 其中第一个隐式参数为对象
- classmethod装饰器, 类方法(给人感觉非常类似于OC中的类方法), 其中第一个隐式参数为类
- staticmethod装饰器, 没有任何隐式参数. python中的静态方法类似与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 object at 0x100ba4e10>, para) executing class_foo(<class '__main__.A'>, para) executing class_foo(<class '__main__.A'>, para) executing static_foo(para) executing static_foo(para)
property装饰器
定义私有类属性
将property与装饰器结合实现属性私有化(更简单安全的实现get和set方法)。
#python内建函数 property(fget=None, fset=None, fdel=None, doc=None)
fget是获取属性的值的函数,fset是设置属性值的函数,fdel是删除属性的函数,doc是一个字符串(像注释一样)。从实现来看,这些参数都是可选的。
property有三个方法getter(), setter()和delete() 来指定fget, fset和fdel。 这表示以下这行:
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 < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value
iter魔法
通过yield和__iter__的结合,我们可以把一个对象变成可迭代的
通过__str__的重写, 可以直接通过想要的形式打印对象
#!/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()
神奇partial
partial使用上很像C++中仿函数(函数对象)。
在stackoverflow给出了类似与partial的运行方式:
def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper
利用用闭包的特性绑定预先绑定一些函数参数,返回一个可调用的变量, 直到真正的调用执行:
#!/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
exec在Python中会忽略返回值, 总是返回None, eval会返回执行代码或语句的返回值
exec和eval在执行代码时, 除了返回值其他行为都相同
在传入字符串时, 会使用compile(source, '
#!/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) # 多行写入
只发一张网上的图, 然后查文档就好了, 这个是记不住的
字符串格式化
一个非常好用, 很多人又不知道的功能:
>>> name = "andrew" >>> "my name is {name}".format(name=name) 'my name is andrew'

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

Sublime 텍스트로 Python 코드를 실행하려면 먼저 Python 플러그인을 설치 한 다음 .py 파일을 작성하고 코드를 작성한 다음 CTRL B를 눌러 코드를 실행하면 콘솔에 출력이 표시됩니다.

Visual Studio Code (VSCODE)에서 코드를 작성하는 것은 간단하고 사용하기 쉽습니다. vscode를 설치하고, 프로젝트를 만들고, 언어를 선택하고, 파일을 만들고, 코드를 작성하고, 저장하고 실행합니다. VSCODE의 장점에는 크로스 플랫폼, 무료 및 오픈 소스, 강력한 기능, 풍부한 확장 및 경량 및 빠른가 포함됩니다.

VS 코드는 파이썬을 작성하는 데 사용될 수 있으며 파이썬 애플리케이션을 개발하기에 이상적인 도구가되는 많은 기능을 제공합니다. 사용자는 다음을 수행 할 수 있습니다. Python 확장 기능을 설치하여 코드 완료, 구문 강조 및 디버깅과 같은 기능을 얻습니다. 디버거를 사용하여 코드를 단계별로 추적하고 오류를 찾아 수정하십시오. 버전 제어를 위해 git을 통합합니다. 코드 서식 도구를 사용하여 코드 일관성을 유지하십시오. 라인 도구를 사용하여 잠재적 인 문제를 미리 발견하십시오.

메모장에서 Python 코드를 실행하려면 Python 실행 파일 및 NPPEXEC 플러그인을 설치해야합니다. Python을 설치하고 경로를 추가 한 후 nppexec 플러그인의 명령 "Python"및 매개 변수 "{current_directory} {file_name}"을 구성하여 Notepad의 단축키 "F6"을 통해 Python 코드를 실행하십시오.
