Python 代码整洁优化

2021-07-16 10:05

阅读:699

标签:数据   add   __init__   info   ber   span   UNC   条件   bsp   

1.提炼函数

# 提炼之前
def user_info():
    users  =  db.session.query(User).all()
    for user in users:
        print(user.name)
        print(user.gender)

# 提炼之后
def user_info():
    users  =  db.session.query(User).all()
    for user in users:
        print_user(user)
 
 
def print_user(user):
    print(user.name)
    print(user.gender)

2.避免不必要的if..else..

# 优化前
def compare(x):
    if x > 8:
        return True
    else:
        return False

# 优化后
def compare(x):
    return x > 8

3.不要对参数赋值

# 优化前
def amount(price,number)
    if number > 40:
        price = 25

# 优化后
def amount(price,number)
    new_price = price
    if number > 40:
        new_price = 25

4.替换逻辑

# 优化前
def func(x):
    if x == "sqlserver":
        return 1
    if x == "oracle":
        return 2
    if x == "pgsql":
        retuen 3
    ...

# 优化后
map_x = {"sqlserver":1,"oracle":2, "pgsql":3}
def func(x):
    return map_x[x]

5.提炼类

# 优化前
class Employee(object):
    def __init__(self, name,gender,addresss, **kwargs):
        self.name = name
        ...
     
    def get_employee_education():
        return self.education
     
    def get_employee_company_info():
        company = Company()
        print company.name
        print company.address

# 优化后
class Employee(object):
    def __init__(self, name,gender,addresss, **kwargs):
 
        self.name = name
        self.company = Company()
        ...
 

    def get_employee_education():
 
        return self.education
 
     
    def get_employee_company_info():
        return self.company.info()

6.以对象代替数组或者字典

# 优化前
user = list()
user.append("name")
user.append("age")
user.append("gender")

# 优化后
user = User()
user.name=""
user.age = ""

7.以常量代替魔法数据

# 优化前
def mianji(r):
    return 3.14 * r * r

# 优化后
PAI = 3.14
def mianji(r):
    return PAI * r * r

8.合并重复的条件片段

# 优化前
if True:
    amount = price * 0.95
    send(amount)
else False:
    amount = price * 0.85
    send(amount)

# 优化后
if True:
    amount = price * 0.95
else False:
    amount = price * 0.85
send(amount)

9.获取数据库表字段,按需要获取

db.session.query(User).all()
 
db.session .query(User.name).all()
 
db.session.query(User).value(User.name)

10.移除不必要的参数

# 如果一些参数在函数体始终用不到,就需要移除

11.将查询函数和修改函数分开

#如将getUserAndAddLog() 替换成
getUser()
addLog()
#函数职责要分明

 

Python 代码整洁优化

标签:数据   add   __init__   info   ber   span   UNC   条件   bsp   

原文地址:https://www.cnblogs.com/songxiaohua/p/9534824.html


评论


亲,登录后才可以留言!