前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pythonic

Pythonic

原创
作者头像
vanguard
修改2021-01-04 10:57:47
3910
修改2021-01-04 10:57:47
举报
文章被收录于专栏:vanguard

PEP 8 -- Style Guide for Python Code

0. 程序必须先让人读懂,然后才能让计算机执行。

“Programs must be written for people to read, and only incidentally for machines to execute.”

1. 交换赋值

代码语言:python
代码运行次数:0
复制
a, b = b, a # 先生成一个元组(tuple)对象,然后unpack

2. Unpacking

代码语言:python
代码运行次数:0
复制
a,*c,d = [1,2,3,4,5]

3. 使用操作符in

代码语言:python
代码运行次数:0
复制
if 0 in [1,2,3]: print(1)

4. 字符串操作

代码语言:python
代码运行次数:0
复制
''.join(['a','b','c'])

5. 字典键值列表

代码语言:python
代码运行次数:0
复制
for key in my_dict: # my_dict[key] ... 
# 只有当循环中需要更改key值的情况下,我们需要使用 my_dict.keys()
# 生成静态的键值列表。

6. 字典键值判断

代码语言:python
代码运行次数:0
复制
if key in my_dict: #...do something with d[key]

7. 字典 get 和 setdefault 方法

代码语言:python
代码运行次数:0
复制
a = {} # update or create
for (b,c) in ((1,2),(2,3)):
    a[b] = a.get(b,0) # if b not in a: a[b]=0
    # a.setdefault(b,0)
print(a)

8. 判断真伪

代码语言:python
代码运行次数:0
复制
if ['a']: print(1)

9. 遍历列表以及索引

代码语言:python
代码运行次数:0
复制
for idx,item in enumerate('a b c'.split()): print(idx,item)

10. 列表推导

代码语言:python
代码运行次数:0
复制
[print(i) for i in range(10) if i%2==0]

11. 列表推导-嵌套

代码语言:python
代码运行次数:0
复制
a = (i for j in range(200) if j%3==0 \
 for i in range(100) if i%3==0)
for b in a: print(b)

12. 循环嵌套

代码语言:python
代码运行次数:0
复制
from itertools import product
[print(x,y,z) for x,y,z in product([1,2],[3,4],[5,6])]

13. 尽量使用生成器代替列表

代码语言:python
代码运行次数:0
复制
def fab(max): 
    n, a, b = 0, 0, 1 
    while n < max: 
        yield b # print(b)
        a, b = b, a + b 
        n = n + 1
for n in fab(5):  print(n)

14. 使用any/all函数

代码语言:python
代码运行次数:0
复制
print(any([False,False]),all([True,True]))

15. 属性(property)

代码语言:python
代码运行次数:0
复制
class Goods(object):
  def __init__(self):  
    self.price = 100  # 原价
    self.discount = 0.8 # 折扣
 
  def get_price(self):
    # 实际价格 = 原价 * 折扣
    new_price = self.price * self.discount
    return new_price
 
  def set_price(self, value):
    self.price = value
 
  def del_price(self):
    del self.price
   # 获取    设置     删除    描述文档
  PRICE = property(get_price, set_price, del_price, '价格属性描述...')
 # 使用此方式设置
  
obj = Goods()
print(obj.PRICE)    # 获取商品价格
obj.PRICE = 200  # 修改商品原价
print(obj.PRICE)
del obj.PRICE   # 删除商品原价

16. 使用 with 处理文件打开

代码语言:python
代码运行次数:0
复制
with open("some_file.txt") as f: data = f.read()

17. 使用 with 处理加锁

代码语言:python
代码运行次数:0
复制
import threading
lock = threading.Lock()
with lock: # 互斥操作...
# lock.acquire()
# try: # 互斥操作...
# finally: lock.release()

18. *Build-in Functions *内置函数

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

dir()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

# string functions

代码语言:python
代码运行次数:0
复制
# str.rpartition()
print('str.rpartition','django.contrib.db'.rpartition(".")[-2:])

# str.isidentifier()
print('obj.isidentifier() is string','django'.isidentifier(),'0'.isidentifier())

# str.replace(a,b)
print('replaced'.replace("d",""))

# str.split(a)
print('split split'.split(" "))

# Object Oriented

代码语言:python
代码运行次数:0
复制
class Test:
    a = None
    def __init__(self): self.a = True
    def __repr__(self): return '__repr__ return class'
    def __str__(self): return '__str__ packed repr for endusers'
    #
    def hasattr(self): return(hasattr(self,'a'),hasattr(self,'b'))
    @property
    def method_with_property(self): return 'method_with_property'
    def method_without_property(self): return 'method_without_property()'

# class >> __new__
test = object.__new__(Test)

# class >>  __repr__ >> __str__
print(test)
print(test.__repr__())
print(test.__str__())

# class >> getattr(self,'a')
print('getattr a:%s' % getattr(test,'a'))
# class >> hasattr(self,'b')
print('hasattr b:%s' % hasattr(test,'b'))

# class >> __init__ >> __dict__
print('__dict__',test.__dict__,test.a)
test.__init__()
print('__dict__',test.__dict__,test.a)

# class >> @property
print(test.method_with_property)
print(test.method_without_property())

# map() 会根据提供的函数对指定序列做映射
print(list(map(lambda x: x * x, list(range(10)))))

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • PEP 8 -- Style Guide for Python Code
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档