gpt4 book ai didi

python - 有什么办法可以改进这个Python函数吗?

转载 作者:行者123 更新时间:2023-11-30 23:58:15 25 4
gpt4 key购买 nike

def __number():
# This line returns the number of the latest created object
# as a "Factura" object in format "n/year"
last = Factura.objects.filter(f_type__exact=False).latest('number')

# We convert it into a string and split it to get only the first number
spl = str(last).split('/')[0]

# Convert it into integer so we can do math
n = int(spl)

# Get the current year
y = date.today().strftime('%y')

# If none return 1/year
if n == None:
return str(1) + '/' + str(y)

# Else we increment the number in one.
else:
n = n + 1
return str(n) + '/' + str(y)

它的作用:它自动生成一个格式为“1/year”“2/year”等的数字。如果用户输入其他数字,例如564/10 函数紧随其后,下一个函数将是 565/10。

即使用户介绍了 p.e. 34/10 在输入 564/10 后,函数将遵循最大的数字。

我这样做对吗还是有更好的方法?

<小时/>

更新:

def __number():
current_year = date.today().strftime('%y')
try:
facturas_emmited = Factura.objects.filter(f_type__exact=False)
latest_object = facturas_emmited.latest('number').__str__()
first_number = int(latest_object.split("/")[0]) + 1
except Factura.DoesNotExist:
first_number = 1
return '%s/%s' % (first_number, current_year)

最佳答案

这实际上只是一个开始,但我首先用自记录代码替换一些注释。

def __number():
# "Factura" object in format "n/year"
latest_object = Factura.objects.filter(f_type__exact=False).latest('number')

# Better name can be available if you explain why the first number is important and what it means
# Do Factura objects not have a __repr__ or __str__ method that you must cast it?
first_number = int(str(latest_object).split('/')[0])
current_year = date.today().strftime('%y')
# Use "is None" rather than "== None"
if first_number is None:
return '1/%d' % current_year
# No else needed because of return above
# Why do we add 1 to first number? Comments should explain _why_, not how
return '%d/%d' % (first_number + 1, current_year)

关于python - 有什么办法可以改进这个Python函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3152913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com