在类中正确定义变量时出现问题

时间:2019-07-13 12:23:51

标签: python-3.x class

新的编码器开发脚本,可用于我的日常工作。试图创建一个类,使用户输入月份和年份并将其组合为日期对象。我可以获取用于日期输入和解析为日期对象工作的代码。但是然后尝试进入一个类,这样我就可以在似乎无法正确实现的不同实例中反复使用。我粘贴了我目前处于反复试验状态的位置。我经历了许多次迭代以使其正常工作。任何建议将不胜感激

见上文

class User_Input_Date():
    def __ini__(self):

        self.month_input = input('What was the month (1-12)').strip()
        if self.month_input in ['01', '1', 'Jan', 'January', 'jan', 'january']:
            self.month_input = 1
        elif self.month_input in ['02', '2', 'Feb', 'February', 'feb', 'february']:
            self.month_input = 2
        elif self.month_input in ['03', '3', 'Mar', 'March', 'mar', 'march']:
            self.month_input = 3
        elif self.month_input in ['04', '4', 'Apr', 'April', 'apr', 'april']:
            self.month_input = 4
        elif self.month_input in ['05', '5', 'May', 'may']:
            self.month_input = 5
        elif self.month_input in ['06', '6', 'Jun', 'June', 'jun', 'june']:
            self.month_input = 6
        elif self.month_input in ['07', '7', 'Jul', 'July', 'jul', 'july']:
            self.month_input = 7
        elif self.month_input in ['08', '8', 'Aug', 'August', 'aug', 'august']:
            self.month_input = 8
        elif self.month_input in [
                '09', '9', 'Sept', 'September', 'sept', 'september'
        ]:
            self.month_input = 9
        elif self.month_input in ['10', 'Oct', 'October', 'oct', 'october']:
            self.month_input = 10
        elif self.month_input in ['11', 'Nov', 'November', 'nov', 'november']:
            self.month_input = 11
        elif self.month_input in ['12', 'Dec', 'December', 'dec', 'december']:
            self.month_input = 12
        else:
            self.month_input = None
        self.year_input = input('What was the year?').strip()

    def Combined_User_Input_Date(self):
        combine_date_user_input_month_year = datetime.date(
            self.year_input, self.month_input, day=1)
        return combine_date_user_input_month_year.strftime("%m" + "-" + "%Y")


primary_bariatric_date = User_Input_Date()
primary_bariatric_date.Combined_User_Input_Date()

告诉我我的年份输入未定义。确切的文字如下:

Traceback (most recent call last):
File "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/test.py", line 64, in <module>
primary_bariatric_date.Combined_User_Input_Date()
File "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/test.py", line 59, in Combined_User_Input_Date
self.year_input, self.month_input, day=1)
AttributeError: 'User_Input_Date' object has no attribute 'year_input'

1 个答案:

答案 0 :(得分:1)

类初始化的问题,只需将__ini__更改为__init__。就是这样。