在python中如何知道类的方法
Ex: import datetime is a module which has a date class in it..
And print datetime.date.today()
将产生今天的日期.
如何知道一个类的所有方法
help(datetime) and dir(datetime) 唯一的方法..?
遵循Björn的回答和Dive-into-Python章节使用callable(getattr(classname)):
>>> import datetime
>>> c=datetime.datetime
>>> methodList = [method for method in dir(c) if callable(getattr(c, method))]
>>> methodList
['__add__', '__class__', '__delattr__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__',
'__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__',
'__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'dst',
'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday',
'now', 'replace', 'strftime', 'strptime', 'time', 'timetuple', 'timetz',
'today', 'toordinal', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset',
'utctimetuple', 'weekday']
Run Code Online (Sandbox Code Playgroud)
>>> methodList = [item for item in dir(c)
if type(getattr(c, item))==type(getattr(c,'__new__'))]
>>> methodList
['__new__', '__subclasshook__', 'combine', 'fromordinal', 'fromtimestamp',
'now', 'strptime', 'today', 'utcfromtimestamp', 'utcnow']
Run Code Online (Sandbox Code Playgroud)
这种技术依赖于以下事实:__new__属性始终是一个方法(它可以被覆盖,但每个其他关键字都可以).