【发布时间】:2020-05-30 18:33:09
【问题描述】:
我的代码中有三个极其相似的函数,它们分别为用户输入他们的出生年、月和日。即使代码非常基本,我也想使用最佳实践,这就是为什么它有点矫枉过正。所以现在我有一个作为模板的函数,它接受三个参数 dateType、typeStr 和 typeFormat。我正在尝试使用这些参数来命名我将使用模板创建的三个函数中的变量,以便以后可以打印出该人的出生日期。我知道范围,但我尝试过让事情全球化等,但它没有奏效。我不知道我是在创建持久的变量,还是在函数完成后所有变量都被取消分配,如果我正在创建变量,我无法弄清楚它们被称为什么,因为我已经尝试了每一个可能性。
def makeTemplateInput(dateType, typeStr, typeFormat):
def templateInput(dateType, typeStr, typeFormat):
print('You\'re using the template function. Please input your birth {} in the format {}.\n$ '.format(dateType, typeFormat), end='')
while True:
try:
dateType = input()
typeStr = dateType
dateType = int(dateType)
if dateType > 0:
if len(typeStr) != len(typeFormat) and isinstance(dateType, int):
print('Your input doesn\'t have {} digits, please use the format {}.\n$ '.format(str(len(typeFormat)), typeFormat), end='')
print('strlen: ' + str(len(typeStr)))
continue
break
else:
print('Your input is not a positive integer!\n$ ', end='')
continue
except ValueError:
print('Your input is not a valid number, please use the format {} where {} is an integer.\n$ '.format(typeFormat, str(typeFormat[:1])), end='')
print(dateType)
def yearInput1():
makeTemplateInput('year', 'yearStr', 'YYYY')
yearInput1()
print('Your birthdate is: {}/{}/{}'.format(yearInput1.year, monthInput.monthStr, dayInput.dayStr))
我敢肯定这是一团糟,误解了 Python 的基本知识,但我真的不明白出了什么问题。
【问题讨论】:
-
makeTemplateInput只是创建一个函数,而不用它做任何事情。好像没必要,删掉就好了。 “我正在尝试使用这些参数来命名我将使用模板创建的三个函数中的变量,以便我以后可以打印出该人的出生日期。”你不能这样做,但你为什么需要呢? -
注意,我将删除 makeTemplateInput。在我发布的最终代码 sn-p 中,您可以看到我想要做的事情,但我不知道如何从使用模板创建的函数中获取这些变量。我希望能够使用模板的 args 或类似的东西来命名函数中的变量,这样我就不必复制/粘贴三个函数。
-
停止思考变量。 对象您在函数之外需要应该以某种形式返回。
-
“我希望能够使用模板的 args 或类似的东西来命名函数中的变量,这样我就不必复制/粘贴三个函数。”为什么需要不同的变量名?
-
我想我不需要不同的变量名,那么我的问题是如何从我新制作的 yearInput1() 中获取一个变量并使用它来打印生日?做 year1Input.anyvariablename 告诉我它没有 anyvariablename 成员。至于您对对象的评论,我不明白 - 不幸的是我还没到那里
标签: python function templates variables dynamic