17가지 Python 트릭과 공유할 수 있는 요령
제한된 인터페이스를 외부
python 타사 패키지를 게시할 때 모든 를 원하지는 않습니다. 코드에서 >Function 또는 class를 외부에서 가져올 수 있습니다. init.py에 all 속성 을 추가하고 목록 가져온 클래스나 함수 이름은 가져오기를 제한하고 다른 함수나 클래스의 외부 가져오기를 방지할 수 있습니다.
#!/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']
컨텍스트 관리 프로토콜 객체 를 지원해야 합니다. > 컨텍스트 관리 프로토콜 Enter 및 Exit의 두 가지 방법이 포함되어 있습니다. with 문은 런타임 컨텍스트를 설정하고 이 두 메서드를 통해 항목 및 종료 작업을 수행해야 합니다. 여기서
context 표현식 은 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(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>
필터 사용법
필터에 비해
map과 Reduce를 더 자주 사용한다. . 필터는 이름과 마찬가지로 특정 규칙에 따라 일부 요소를 필터링합니다. #!/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로그인 후 복사
클래스에는 일반적으로 사용되는 두 가지 장식이 있습니다. 먼저 구별해 보겠습니다.
첫 번째 암시적 매개 변수는- 객체인 일반 멤버 함수입니다.
- , 클래스 메서드(OC의 클래스 메서드와 매우 유사한 느낌), 첫 번째는 암시적입니다. 매개변수는
입니다. class
정적 메서드 데코레이터 - , 암시적 매개변수 없이
static 메서드는 정적 메서드와 유사합니다. 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>
로그인 후 복사
- 속성 결합 데코레이터를 사용하여 속성을 사유화합니다( get 및
메서드 구현이 더 간단 더 안전 ). #python内建函数
property(fget=None, fset=None, fdel=None, doc=None)
문자열 (예: 참고 동일). 구현 관점에서 이러한 매개변수는 선택사항입니다. 속성에는 fget, fset 및 fdel을 지정하는 getter(), setter() 및 delete
() 세 가지 메소드가 있습니다. 이는 다음 줄을 의미합니다.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
-
으로 바꿀 수 있습니다.
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()
로그인 후 복사
overflow
에서는 부분과 유사한 작업 방법이 제공됩니다.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, ‘string>’, 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) # 多行写入
各种时间形式转换
只发一张网上的图, 然后查文档就好了, 这个是记不住的
字符串格式化
一个非常好用, 很多人又不知道的功能:
>>> name = "andrew" >>> "my name is {name}".format(name=name) 'my name is andrew'
위 내용은 17가지 Python 트릭과 공유할 수 있는 요령의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

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

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

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

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

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

뜨거운 주제











많은 웹 사이트 개발자는 램프 아키텍처에서 Node.js 또는 Python 서비스를 통합하는 문제에 직면 해 있습니다. 기존 램프 (Linux Apache MySQL PHP) 아키텍처 웹 사이트 요구 사항 ...

SCAPY 크롤러를 사용할 때 파이프 라인 영구 스토리지 파일을 작성할 수없는 이유는 무엇입니까? 토론 Data Crawler에 Scapy Crawler를 사용하는 법을 배울 때 종종 ...

Python Process Pool은 클라이언트가 갇히게하는 동시 TCP 요청을 처리합니다. 네트워크 프로그래밍에 Python을 사용하는 경우 동시 TCP 요청을 효율적으로 처리하는 것이 중요합니다. ...

functools.partial in Python의 파이썬 funcTools.partial 객체의 시청 방법을 깊이 탐구하십시오 ...

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Python 크로스 플랫폼 데스크톱 응용 프로그램 개발 라이브러리 선택 많은 Python 개발자가 Windows 및 Linux 시스템 모두에서 실행할 수있는 데스크탑 응용 프로그램을 개발하고자합니다 ...

Python : 모래 시계 그래픽 도면 및 입력 검증을 시작 하기이 기사는 모래 시계 그래픽 드로잉 프로그램에서 Python 초보자가 발생하는 변수 정의 문제를 해결합니다. 암호...

데이터 변환 및 통계 : 대규모 데이터 세트의 효율적인 처리이 기사는 제품 정보가 포함 된 데이터 목록을 다른 사람으로 변환하는 방법을 자세히 소개합니다 ...
