Python中的dir函数
dir([object]) -> list of strings If called without an argument, return the names in the current scope. 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.
help(dir):
我发现可能在内置函数 dir
的帮助文件里有一些问题。例如:
class AddrBookEntry(object):
'address book entry class'
def __init__(self,nm,ph):
self.name=nm
self.phone=ph
def updatePhone(self,newph):
self.phone=newph
print 'Updated phone # for :' ,self.name
dir(AddrBookEntry('tom','123'))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'phone', 'updatePhone']
1. dir()
不仅可以列出对象的属性,还可以列出对象的方法。
比如 updatePhone
是一个方法,不是属性。
2. 我怎么知道在 dir()
的输出中,哪些是属性,哪些是方法呢?
4 个回答
1
帮助文件说得没错。在Python中,方法和类(以及这些类的实例)是以和其他属性完全一样的方式关联在一起的。为了区分一个普通属性和一个可以调用的方法,你需要对它进行解引用:
>>> type(AddrBookEntry('tom','123').phone)
<type 'str'>
>>> type(AddrBookEntry('tom','123').updatePhone)
<type 'instancemethod'>
2
你可以通过感觉来区分它们,但方法其实就是属性,所以要想完全确定,还是得检查一下。
这里有个函数可以帮你搞清楚:
def dirf(obj=None):
"""Get the output of dir() as a tuple of lists of callables and non-callables."""
d = ([],[])
for name in dir(obj):
if callable(getattr(obj, name, locals().get(name))):
d[0].append(name)
else:
d[1].append(name)
return d
inspect.getmembers
提供了一个很方便的方式来获取可调用的成员:
from inspect import getmembers
getmembers(obj, callable)
不过要小心它自己的判断标准!inspect.ismethod
只会对那些在 Python 中实现的方法返回 True
。很多核心对象的方法(比如 [].sort
)并不符合这个标准。
2
在Python中,方法其实就是属性。
可以查看它们的各种属性。方法有一些以
im_*
开头的属性。