类-Python中的方法

时间:2011-04-06 11:26:40

标签: python

在python中如何知道类的方法

Ex: import datetime is a module which has a date class in it.. And print datetime.date.today()

将产生今天的日期。

如何知道类的所有方法

help(datetime) and dir(datetime)是唯一的方法..?

4 个答案:

答案 0 :(得分:5)

第一个解决方案

关注Björn's answerDive-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']

第二个解决方案 - 阅读Guandalino的评论后

>>> 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)

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.

>>> 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']
>>>