我为练习编写了一个简单的日期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
答案 0 :(得分:1)
为了使用&#34;全球&#34;您的类中的变量,将变量分配给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
>>>