这里有新鲜出炉的Python教程,程序狗速度看过来!
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
这篇文章主要给大家介绍了关于python如何利用dir函数查看类中所有成员函数的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用python具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习下吧。
前言
如果一个类是别人编写的,又没有帮助文档,怎么样来查看所有成员函数呢?本文详细给大家介绍了关于python用dir函数查看类中所有成员函数的相关内容,下面话不多说了,来一起看看详细的介绍吧。
可以使用下面的代码:
- # File: builtin-dir-example-2.py
- class A:
- def a(self):
- pass
- def b(self):
- pass
- class B(A):
- def c(self):
- pass
- def d(self):
- pass
- def getmembers(klass, members=None):
- # get a list of all class members, ordered by class
- if members is None:
- members = []
- for k in klass.__bases__:
- getmembers(k, members)
- for m in dir(klass):
- if m not in members:
- members.append(m)
- return members
- print('A=> :', getmembers(A))
- print()
- print('B=> :', getmembers(B))
- print()
- print('IOError=> :', getmembers(IOError))
输出结果如下:
- >>>
- ==== RESTART: D:/work/csdn/python_Game1/example/builtin-dir-example-2.py ====
- A=> : ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__dict__', '__module__', '__weakref__', 'a', 'b']
- B=> : ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__dict__', '__module__', '__weakref__', 'a', 'b', 'c', 'd']
- IOError=> : ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__cause__', '__context__', '__dict__', '__setstate__', '__suppress_context__', '__traceback__', 'args', 'with_traceback', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'winerror']
- >>>
在这个例子里,输出基类A的成员函数,输出派生类B的成员函数。
dir()内置函数作用
python内置方法有很多,无论是初学还是经通python的程序员都不能全部记住所有方法,这时候dir()函数就非常有用了。使用dir()函数可以查看对像内所有属于及方法,在python中任何东西都是对像,一种数据类型,一个模块等,都有自己的属性和方法,除了常用方法外,其它的你不需要全部记住它,交给dir()函数就好了。
dir()函数使用方法
dir()函数操作方法很简单,只需要把你想要查询和对像添写到( )括号中就可以使用了。
例如你想查看列表都有哪些方法,你可以在( )中直接传入空列表对像[ ]或是一个列表数据类型的变量名,像下边这样操作:
- >>> dir([])
或
- x = ['a','b']
- >>>dir(x)
两种操作方法所得结果一样,都是查看列表都有哪些操作方法及属性的。如果你想查字符串,只要把()中的参数变量名或空字符串' '就可以了。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对PHPERZ的支持。
来源: http://www.phperz.com/article/17/1027/350917.html