Python idioms, 2 of n

来源:互联网 发布:淘宝店铺怎样设置积分 编辑:程序博客网 时间:2024/05/22 00:56
1) Don't do trivial assignment in __init__ of the class
Don't:
class Foo(object):
    def __init__(self):
        self.attr1 = 0
        self.attr2 = ''
        self.attr3 = []
        self.attr4 = {}

Do:
class Foo(object):   // Define the member variables when first used in the code
    def __init__(self):
        ...


2)
Try coding like this:
for work_request in iter(queue.get, sentinel):
    process_work_request(work_request)

Compare:
while True:
    work_request = queue.get()
    if work_request == sentinel:
        break
    process_work_request(work_request)

3) Always put parentheses around "conditoinal expression"
x = (true_value if condition else false_value)
Refer to
http://www.python.org/dev/peps/pep-0308/


Reference

http://blog.csdn.net/lanphaday/article/details/2905877
原创粉丝点击