在python中如何知道类的方法
Ex: import datetime is a module which has a date class in it..
And print datetime.date.today()
将产生今天的日期。
如何知道类的所有方法
help(datetime) and dir(datetime)
是唯一的方法..?
答案 0 :(得分:5)
关注Björn's answer和Dive-into-Python chapter使用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']
>>> 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']
这种技术依赖于__new__
属性始终是一个方法(它可以被覆盖,但每个其他关键字都可以)的事实。
答案 1 :(得分:2)
在python中,这称为Introspection
,您可以看到它的一些示例here。
答案 2 :(得分:2)
>>> from datetime import datetime
>>> import pprint, inspect
>>> predicate = inspect.ismethoddescriptor
>>> methods = inspect.getmembers(datetime, predicate=inspect.ismethod)
>>> descriptors = inspect.getmembers(datetime, predicate=inspect.ismethoddescriptor)
>>> methods.extend(descriptors)
>>> methods = [method[0] for method in methods]
>>> pprint.pprint(methods)
['__add__',
'__delattr__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__lt__',
'__ne__',
'__radd__',
'__reduce__',
'__reduce_ex__'
'__repr__',
'__rsub__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'astimezone',
'ctime',
'date',
'dst',
'isocalendar',
'isoformat',
'isoweekday',
'replace',
'strftime',
'time',
'timetuple',
'timetz',
'toordinal',
'tzname',
'utcoffset',
'utctimetuple',
'weekday']
答案 3 :(得分:0)
>>> class A(object):
def __init__(self):
self.field=1
class B(object):
pass
self.myclass=B
self.myinstance=B()
def mymethod(x):
print x
>>> a=A()
>>> import inspect
>>> methods=[name for name in dir(a) if inspect.ismethod(getattr(a,name))]
>>> methods
['__init__', 'mymethod']
>>>