3.6.0中的python对象创建

时间:2017-04-13 14:09:34

标签: python class object

我刚刚介绍了python中的Classes。程序用于计算给出日期的新日期和添加到日期的天数。我正在运行给定的代码,但我收到无效的语法错误,但没有指定行号。谁能解释有什么不对? 谢谢! 代码在python 3.6.0中

class Date(object):
months={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
def __init__(self):
    self.date=0
    self.month=0
    self.year=0
    self.leap=False
    self.enter()
def enter(self):
    self.date=int(input("Enter the date: "))
    self.month=int(input("Enter the month: "))
    self.year=int(input("Enter the year: "))
    if self.year%4==0:
        if self.year%100==0:
            break
        self.leap=True
        months[2]=29
def __add__(self,day=int(input("Enter the number of days: "))):
    self.date+=day
    c=0
    for i in range(12):
        self.date-=Date.months[i+1]
        if self.date<1:
            self.date+=Date.months[i+1]
            break
        c+=1
    self.month+=c
    if self.month>12:
        self.year+=1
        self.month=self.month//12
    print(self.date,'/',self.month,'/',self.year
#main
ob1=Date()

1 个答案:

答案 0 :(得分:0)

您应该在您的代码中修复缩进问题:

class Date(object):
    months={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
    def __init__(self):
        self.date=0
        self.month=0
        self.year=0
        self.leap=False
        self.enter()
    def enter(self):
        self.date=int(input("Enter the date: "))
        self.month=int(input("Enter the month: "))
        self.year=int(input("Enter the year: "))
        if self.year%4==0:
            if self.year%100==0:
                pass
            self.leap=True
            months[2]=29
    def __add__(self,day=int(input("Enter the number of days: "))):
        self.date+=day
        c=0
        for i in range(12):
            self.date-=Date.months[i+1]
            if self.date<1:
                self.date+=Date.months[i+1]
                break
            c+=1
        self.month+=c
        if self.month>12:
            self.year+=1
            self.month=self.month//12
        print(self.date,'/',self.month,'/',self.year)
#main
ob1=Date()

此外,您无法在break循环之外使用for。将其更改为pass或其他内容。

此外,我建议您查看PEP8样式指南here,以使您的代码更具可读性。