前言
python中的模块定义与调用,趁着国庆假期空闲,深入研究研究!
提示:以下是本篇文章正文内容,下面案例可供参考
一、模块是什么?
Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。
模块让你能够有逻辑地组织你的 Python 代码段。
把相关的代码分配到一个模块里能让你的代码更好用,更易懂。
模块能定义函数,类和变量,模块里也能包含可执行的代码。
二、关于模块的几个知识点
1.模块导入
- import module_name
- from module_name import def
- from module_name import * (其中 *号,导入模块定义的__all__常量中的API),举个例子,如下:
calendar模块定义, calendar.py:
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
"monthcalendar", "prmonth", "month", "prcal", "calendar",
"timegm", "month_name", "month_abbr", "day_name", "day_abbr"]
calendar_demo.py中导入模块,就会导入 __all__中所有方法:
# -*- coding:utf-8 -*-
from calendar import *
print(monthcalendar(2021, 10))
2.模块方法
同样看calendar模块定义,calendar.py:
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isleap(year):
"""Return True for leap years, False for non-leap years."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def weekday(year, month, day):
"""Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
day (1-31)."""
return datetime.date(year, month, day).weekday()
调用calendar模块方法与常量,calendar_demo.py:
# -*- coding:utf-8 -*-
import calendar
mdays = calendar.mdays #读取calendar模块中定义的常量mdays
print(mdays)
d_isleap = calendar.isleap(2021) #判断瑞年
print(d_isleap)
d_weekday = calendar.weekday(2021, 10, 6) #返回星期几
print(d_weekday)#Return weekday (0-6 ~ Mon-Sun)
3.类普通方法调用
同样看calendar模块定义,calendar.py:
class Calendar(object):
"""
Base calendar class. This class doesn't do any formatting. It simply
provides data to subclasses.
"""
def __init__(self, firstweekday=0):
self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
def monthdatescalendar(self, year, month):
"""
Return a matrix (list of lists) representing a month's calendar.
Each row represents a week; week entries are datetime.date values.
"""
dates = list(self.itermonthdates(year, month))
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
class TextCalendar(Calendar):
"""
Subclass of Calendar that outputs a calendar as a simple plain text
similar to the UNIX program cal.
"""
调用calendar模块方法与常量,calendar_demo.py:
# -*- coding:utf-8 -*-
import calendar
print("--------------------------------------------------")
calendar_obj = calendar.Calendar(firstweekday=1)
ca = calendar_obj.monthdatescalendar(2021, 10) #返回当月日历
print(ca)
print("*************************************************")
textCalendar_obj = calendar.TextCalendar(firstweekday=0)
ca_text = textCalendar_obj.monthdatescalendar(2021, 10) #返回当月日历
print(ca_text)
4.类方法调用,@classmethod修饰方法
同样看datetime模块定义,datetime.py:
class date:
"""Concrete date type.
Constructors:
__new__()
fromtimestamp()
today()
fromordinal()
Operators:
__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__
__add__, __radd__, __sub__ (add/radd only with timedelta arg)
Methods:
timetuple()
toordinal()
weekday()
isoweekday(), isocalendar(), isoformat()
ctime()
strftime()
Properties (readonly):
year, month, day
"""
__slots__ = '_year', '_month', '_day', '_hashcode'
def __new__(cls, year, month=None, day=None):
"""Constructor.
Arguments:
year, month, day (required, base 1)
"""
if month is None and isinstance(year, bytes) and len(year) == 4 and \
1 <= year[2] <= 12:
# Pickle support
self = object.__new__(cls)
self.__setstate(year)
self._hashcode = -1
return self
year, month, day = _check_date_fields(year, month, day)
self = object.__new__(cls)
self._year = year
self._month = month
self._day = day
self._hashcode = -1
return self
# Additional constructors
@classmethod
def fromtimestamp(cls, t):
"Construct a date from a POSIX timestamp (like time.time())."
y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
return cls(y, m, d)
@classmethod
def today(cls):
"Construct a date from time.time()."
t = _time.time()
return cls.fromtimestamp(t)
调用datetime模块中date类中方法,datetime_date_demo.py:
# -*- coding:utf-8 -*-
from datetime import date
d_new = date(2021, 10, 6) #根据date类中 __new__方法,实例化一个date对象
print(d_new)
#调用@classmethod(类方法),不用实例化对象,可直接调用方法
d_fromtimestamp = date.fromtimestamp(1000) #以UniX元年开始,转换时间戳为对应日期
print(d_fromtimestamp)
d_today = date.today() #返回今天日期
print(d_today)
5.模块中实例化的类方法调用
同样看calendar模块定义,calendar.py:
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
"monthcalendar", "prmonth", "month", "prcal", "calendar",
"timegm", "month_name", "month_abbr", "day_name", "day_abbr"]
class Calendar(object):
"""
Base calendar class. This class doesn't do any formatting. It simply
provides data to subclasses.
"""
def __init__(self, firstweekday=0):
self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
def monthdatescalendar(self, year, month):
"""
Return a matrix (list of lists) representing a month's calendar.
Each row represents a week; week entries are datetime.date values.
"""
dates = list(self.itermonthdates(year, month))
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
class TextCalendar(Calendar):
"""
Subclass of Calendar that outputs a calendar as a simple plain text
similar to the UNIX program cal.
"""
# Support for old module level interface
c = TextCalendar()
monthcalendar = c.monthdayscalendar
调用calendar模块中方法,calendar_demo.py:
# -*- coding:utf-8 -*-
import calendar
#普通调用方法:先实例化,再调用类方法
ca_text_obj = calendar.TextCalendar(firstweekday=0)
ca_text = ca_text_obj.monthdayscalendar(2021, 10)
print(ca_text)
#既然在模块中已经实例化,直接使用如下方式调用
ca_text_instantiate = calendar.monthcalendar(2021, 10)
print(ca_text_instantiate)
特别注意如上定义方式:直接在模块中实例化类,将类赋值给一个属性,并将该属性放在__all__中导入,当然如上还有类的集成等
6.模块中@property方法
同样看datetime模块定义,datetime.py:
class date:
"""Concrete date type.
Constructors:
__new__()
fromtimestamp()
today()
fromordinal()
Operators:
__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__
__add__, __radd__, __sub__ (add/radd only with timedelta arg)
Methods:
timetuple()
toordinal()
weekday()
isoweekday(), isocalendar(), isoformat()
ctime()
strftime()
Properties (readonly):
year, month, day
"""
__slots__ = '_year', '_month', '_day', '_hashcode'
def __new__(cls, year, month=None, day=None):
"""Constructor.
Arguments:
year, month, day (required, base 1)
"""
if month is None and isinstance(year, bytes) and len(year) == 4 and \
1 <= year[2] <= 12:
# Pickle support
self = object.__new__(cls)
self.__setstate(year)
self._hashcode = -1
return self
year, month, day = _check_date_fields(year, month, day)
self = object.__new__(cls)
self._year = year
self._month = month
self._day = day
self._hashcode = -1
return self
# Read-only field accessors
@property
def year(self):
"""year (1-9999)"""
return self._year
@property
def month(self):
"""month (1-12)"""
return self._month
@property
def day(self):
调用datetime模块中方法,datetime_date_demo.py:
# -*- coding:utf-8 -*-
import datetime
d_new = datetime.date.today() #实例化一个date
print(d_new)
#私有访问器
d_new_year = d_new.year #方法通过属性方式访问, 返回当前日期年份
print(d_new_year)
d_new_month = d_new.month #方法通过属性方式访问, 返回当前日期月份
print(d_new_month)
d_new_day = d_new.day #方法通过属性方式访问, 返回当前日期日
print(d_new_day)
三、自定义模块
python中带有__init__.py的文件夹称之为模块,以下模块定义【加入专门的api文件】
- 模块定义
- 模块调用
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。