【问题标题】:How to create and access dynamic variable names a template function?如何创建和访问模板函数的动态变量名称?
【发布时间】: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


【解决方案1】:

一些在线课程或一些好书可以帮助解决一些这种困惑。我创建了一些示例代码,希望能回答您的问题。谢谢你。

class Calendar:
    def __init__(self, day, month, year): #This can be initialised with the day/month/year
        self.day = day
        self.month = month
        self.year = year

    def displayDate(self): #This will display the dates from the object created/set
        print('day:{} month:{} year:{}'.format(self.day, self.month, self.year))

    def setNewDate(self, otherDay, otherMonth, otherYear): #this sets the class attributes to something else
        print('This was the old values day:{} month:{} year:{}'.format(self.day, self.month, self.year))
        self.day = otherDay
        self.month = otherMonth
        self.year = otherYear
        print('The new values are day:{} month:{} year:{}'.format(self.day, self.month, self.year))

cal = Calendar(6,11,2020)
cal.displayDate()
cal.setNewDate(3,4,2099)

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2012-11-22
    • 1970-01-01
    • 2018-02-28
    • 2022-04-26
    • 2019-07-25
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    相关资源
    最近更新 更多