在后台回复【阅读书籍】
即可获取python相关电子书~
Hi,我是山月。
之前在Python自动化办公:xlwt万字教程里介绍了xlwt的六大样式:数字、字体、对齐、边框、填充、保护。
但是对于新手,最大的困难就是在没有学习文档的情况下不知道可以使用哪些方法与参数。
本着授人以鱼不如授人以渔的心态,今天就来给大家分享下山月的方法~
01
dir函数
dir函数是68个python内置函数中的一个(👉建议收藏:68个Python内置函数详解)~
下面我们更具体的来看看这个函数吧~
1.1、dir函数是什么
我们先用help函数(同样也是68个内置函数中的一个)来查看dir函数的介绍:
help(dir)
运行结果:
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
如此我们可以得知:
1)语法
dir([object]) #object:要查询的对象
2)功能
dir函数返回一个属性列表,其中列表的元素都是字符串格式。
对于模块对象:返回模块的所有属性(变量名和方法)
对于类对象:返回这个类的属性,以及其所有父类(包括父类的父类)的属性
对于其它对象(实例对象):返回这个实例对象的属性,实例对象类的属性,以及这个类的所有父类(包括父类的父类)的属性
1.2、实例讲解
比如,我们查看列表的属性。
方法1:cmd窗口
方法2:IDE(VSCode)
list_example = ['山', '月', '学', 'python']
print(dir(list_example))
运行结果:
ps:返回的__xx__属性在Python 中都是有特殊用途的。比如__add__是相加,__len__是获取长度。
来看看list_example 的属性应用吧:
list_example = ['山', '月', '学', 'python']
list_long = list_example.__len__() #获取列表长度
print(list_long)
list_add = ['!']
list_result = list_example.__add__(list_add) #把两个列表元素相加
print(list_result)
list_example.append(list_add) #把列表list_add作为元素添加到列表list_example
print(list_example)
运行结果:
4
['山', '月', '学', 'python', '!']
['山', '月', '学', 'python', ['!']]
对于我们平时用的len()与__len__()的区别:我们在使用len() 函数的时候,它会自动去调用对象的__len__()方法。
02
获取xlwt样式属性
2.1、边框样式属性
我们以边框样式为例来看看吧~
import xlwt
borders = xlwt.Borders() #定义一个边框实例
print(dir(borders))
对于返回的内容眼熟吗:
如果大家只想看边框的样式类型,我们可以:
import xlwt
list_i = []
for i in dir(xlwt.Borders):
if not i.startswith('_'): #去掉以_开头的
list_i.append(i)
print(list_i)
# #也可以用下面三行代码完成
# import xlwt
# border_style = [i for i in dir(xlwt.Borders) if not i.startswith('_')]
# print(border_style)
结果是:
2.2、工作表属性
在Python自动化办公:xlwt万字教程,我们只介绍了样式,对于工作表的一些设置如冻结窗口等并没有介绍。
现在我们先通过dir函数看看工作表有哪些属性。
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('sheet1')
print(dir(ws))
结果:
看到这一大块不要被吓到哦~我们不需要每个都掌握,只需要掌握其中一些较常用的即可。
下次我们会基于这些属性来介绍一些工作表常用的设置~不见不散啦。
已经到底啦~(≧▽≦*)/~
往 期 推 荐
![156b13f63e88e982441322f580f1f440.png](https://img-blog.csdnimg.cn/img_convert/156b13f63e88e982441322f580f1f440.png)
![e7d210775f8c6dac593e0970f132a260.png](https://img-blog.csdnimg.cn/img_convert/e7d210775f8c6dac593e0970f132a260.png)
![81a3bb152d24471d1c01e341d7d89929.png](https://img-blog.csdnimg.cn/img_convert/81a3bb152d24471d1c01e341d7d89929.png)
点击阅读原文,获得更多精彩内容