将 class 的对象传递给 class 中的方法

Passing an object of a class to a method in the class

我写了一个简单的日期 class 作为练习,但我似乎无法将 class 中的对象传递给 class 中的方法。 class 应该能够接受测试日期,如果它们超出范围则更正它们,然后打印正确的日期。这是代码

class Date:
    month = int
    day = int
    year = int
    def setDate(self, month, day, year)
        HIGH_MONTH = 12
        HIGHEST_DAYS = ['none',31,29,31,30,31,30,31,31,30,31,30,31]
        if month > HIGH_MONTH:
            month = HIGH_MONTH
        elif month < 1:
            month = 1
        else:
            month = month
        if day > HIGHEST_DAYS[month]:
            day = HIGHEST_DAYS[month]
        elif day < 1:
            day = 1
        else:
            day = day
    def showDate(self):
        print 'Date:',month,'/',day,'/',year


#These are my tests
birthday=Date()
graduation=Date()
birthday.month=6
birthday.day=24
birthday.year=1984
graduation.setDate(5,36,2016)
birthday.showDate()
graduation.showDate()

我得到的是NameError: global name 'month' is not defined

为了让您在 class 中使用 "global" 变量,请将变量分配给 self.variable_name,如下所示:

class Date:
    month = int
    day = int
    year = int
    def setDate(self, month, day, year):
        HIGH_MONTH = 12
        HIGHEST_DAYS = [None,31,29,31,30,31,30,31,31,30,31,30,31]
        if month > HIGH_MONTH:
            month = HIGH_MONTH
        elif month < 1:
            month = 1
        else:
            month = month
        if day > HIGHEST_DAYS[month]:
            day = HIGHEST_DAYS[month]
        elif day < 1:
            day = 1
        else:
            day = day
        self.year = year
        self.month = month
        self.day = day
    def showDate(self):
        print 'Date:',self.month,'/',self.day,'/',self.year

>>> birthday=Date()
>>> graduation=Date()
>>> birthday.month=6
>>> birthday.day=24
>>> birthday.year=1984
>>> graduation.setDate(5,36,2016)
>>> birthday.showDate()
Date: 6 / 24 / 1984
>>> graduation.showDate()
Date: 5 / 31 / 2016
>>>