"""
需要计算出某个月内星期几有几天,输入(年份,weekday)
weekday是指0-6,0代表星期一,6代表星期日,
求结果,运行后总抱怨
TypeError: monthdays2calendar() missing 1 required positional argument: 'month'
问题出在哪里?
"""
import calendar
class MyCalendar(calendar.Calendar):
def __init__(self,month):
self.__month=month
self.__count=0
def count_weekday_in_year(self,year,weekday):
self.__year=year
self.__weekday=weekday
for data in MyCalendar.monthdays2calendar(self.__year,self.__month):
if data[1]==self.__weekday:
self.__count+=1
return self.__count
object1=MyCalendar(3)
print(object1.count_weekday_in_year(2019,0))
用下面的
import calendar
class MyCalendar(calendar.Calendar):
def __init__(self,month):
self.__month=month
self.__count=0
super().__init__()##要初始化基类
def count_weekday_in_year(self,year,weekday):
self.__year=year
self.__weekday=weekday
#通过类名称调用需要传入self对象,或者改为self.monthdays2calendar(self.__year,self.__month):,通过实例调用
for weekdays in MyCalendar.monthdays2calendar(self,self.__year,self.__month):
for date in weekdays:#monthdays2calendar返回的是七个元组的列表,其中每个元组都由日期和星期几组成。所以还得遍历一次
if date[0]!=0 and date[1]==self.__weekday:#注意不是本月的日期为0
self.__count+=1
return self.__count
object1=MyCalendar(6)
print('2022-6星期一天数:')
print(object1.count_weekday_in_year(2022,0))
object1=MyCalendar(5)
print('2022-5星期一天数:')
print(object1.count_weekday_in_year(2022,0))