python之coding style

本文提供了编程中的关键技巧和最佳实践,包括变量命名、代码格式、函数设计、字符串操作、列表与字典处理、条件判断及函数编写等,旨在帮助开发者提高代码质量和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义private

外部不需要的对象全部定义为private,只有外部需要引用函数才定义成public(往往将有主要功能的对象全都定义为private,然后定义一个public指向它,提供接口) 

 

分隔长行
折叠长行的首选方法是使用Pyhon支持的圆括号,方括号(brackets)和花括号(braces)内的行延续.
如果需要,你可以在表达式周围增加一对额外的圆括号, 但是有时使用反斜杠看起来更好.确认恰当得缩进了延续的行

#Bad
my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
when I had put out my candle, my eyes would close so quickly that I had not even \
time to say “I’m going to sleep.”"""
from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
yet_another_nice_function

#Good
my_very_big_string = (
"For a long time I used to go to bed early. Sometimes, "
"when I had put out my candle, my eyes would close so quickly "
"that I had not even time to say “I’m going to sleep.”"
)
from some.deep.module.inside.a.module import (
a_nice_function, another_nice_function, yet_another_nice_function)

 

空行:
用两行空行分割顶层函数和类的定义。类内方法的定义用单个空行分割. 在'class'行和第一个方法定义之间也要有一个空行.

空格
spam( ham[ 1 ], { eggs: 2 } ) 改成 spam(ham[1], {eggs: 2})
始终在运算符两边放置一个空格
不要在用于指定关键字参数或默认参数值的'='号周围使用空格. def hello(string='hello')

 

字符串处理

 如果是创建一个新字符串,用+不错.但如果是修改已有字符串,则用join()更有效率. 而且用 list comprehensions 比 append() 更有效率.

foo = 'foo'
bar = 'bar'
foobar = foo + bar  # This is good
foo += 'ooo'  # This is bad, instead you should do:
foo = ''.join([foo, 'ooo'])

# Bad
nums = ""
for n in range(20):
nums += str(n)
# slow and inefficient
print nums

# Good
nums = []
for n in range(20):
nums.append(str(n))
print "".join(nums)  # much more efficient

# Best
nums = [str(n) for n in range(20)]
print "".join(nums)

+, join()也可用%s, format()取代(建议format()) 

foo = 'foo'
bar = 'bar'
foobar = '%s%s' % (foo, bar) # It is OK
foobar = '{0}{1}'.format(foo, bar) # It is better
foobar = '{foo}{bar}'.format(foo=foo, bar=bar) # It is best

 

列表

# Bad
a = [3, 4, 5]
b = []
for i in a:
    if i > 4:
        b.append()
        
# Good
a = [3, 4, 5]
b = [i for i in a if i > 4]
# or
b = filter(lambda x: x > 4, a)

 

字典

# Good
d = {'hello': 'world'}
print d.get('hello', 'default_value') # prints 'world'
print d.get('thingy', 'default_value') # prints 'default_value'
# Or
if 'hello' in d:
    print d['hello']

 

函数

函数尽量保持一个出口(方便debug)

def complex_function(a, b, c):
    if not a:
        return None  # Raising an exception might be better
    if not b:
        return None  # Raising an exception might be better
    # Some complex code trying to compute x from a, b and c
    if not x:
    # Some Plan-B computation of x
    return x  # One single exit point for the returned value x will help when maintaining the code.

 

条件判断

# Bad
if attr == True:
    print 'True!'
if attr == None:
    print 'attr is None!'

# Good
if attr:
    print 'attr is truthy!'

 

 

2015-05-15

 

转载于:https://www.cnblogs.com/whuyt/p/4505234.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值