题
鉴于蟒蛇的对象的任何一种,是有一个简单的方法来获得列表中的所有方法,这一目的?
或者,
如果这是不可能的,有至少一个简单的方式来检查它是否有一个特定方法比简单地检查,如果发生错误的当方法被称为?
解决方案
它的出现可以使用这个代码,代替"对象"的对象是感兴趣的是:
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
我发现了它 这个网站.我们希望,这应该提供一些进一步的细节!
其他提示
你可以使用建立在 dir()
功能得到一个列表中的所有特性的模块。试试这个命令行要看看它是如何工作的。
>>> import moduleName
>>> dir(moduleName)
此外,您可以使用 hasattr(module_name, "attr_name")
能找出如果一个模块具有特定的属性。
看看 导向Python反省 更多的信息。
最简单的方法是使用 dir(objectname)
.这将显示所有方法可用于该目的。凉爽的伎俩。
到检查,如果它有一个特定的方法:
hasattr(object,"method")
我相信,你想要什么,是这样的:
一个列表中的从属性的一个目
在我的愚见,建立在功能 dir()
可以做这份工作给你的。采取从 help(dir)
出于您的Python Shell:
dir(...)
dir([object]) -> list of strings
如果被称为没有一个论点,返回的名字在目前的范围。
还有,返回一个按字母顺序排列的名字包括(一)属性的给予对象,并属性可从它。
如果象提供一种名为
__dir__
, 它将使用;否则 默认dir()逻辑使用和返回:
- 对于一个模块,对象:该模块的属性。
- 一流的对象:它的属性,并递归属性的基础。
- 对于任何其他目的:它的属性、其类的属性, 递归属性的其类的基本课程。
例如:
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "I am a string"
>>>
>>> type(a)
<class 'str'>
>>>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'_formatter_field_name_split', '_formatter_parser', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
因为我检查你的问题,我决定展示我的思路,有一个更好的格式的输出 dir()
.
dir_attributes.py (Python2.7.6)
#!/usr/bin/python
""" Demonstrates the usage of dir(), with better output. """
__author__ = "ivanleoncz"
obj = "I am a string."
count = 0
print "\nObject Data: %s" % obj
print "Object Type: %s\n" % type(obj)
for method in dir(obj):
# the comma at the end of the print, makes it printing
# in the same line, 4 times (count)
print "| {0: <20}".format(method),
count += 1
if count == 4:
count = 0
print
dir_attributes.py (Python3.4.3)
#!/usr/bin/python3
""" Demonstrates the usage of dir(), with better output. """
__author__ = "ivanleoncz"
obj = "I am a string."
count = 0
print("\nObject Data: ", obj)
print("Object Type: ", type(obj),"\n")
for method in dir(obj):
# the end=" " at the end of the print statement,
# makes it printing in the same line, 4 times (count)
print("| {:20}".format(method), end=" ")
count += 1
if count == 4:
count = 0
print("")
希望我已经促成了:).
如果你特别想要 方法, 你应该使用 检查。ismethod.
对于方法的名称:
import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]
该方法本身:
import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]
有的时候 inspect.isroutine
可能是有用的过(对于建立程序,C扩展,Cython没有"约束力"编译器directive)。
开bash(ctrl+alt T上Ubuntu).开始python3壳。创建对象的观察方法。只是添加一个圆点后,按两次"标签",你就会看到类似的东西:
user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__( s.__rmod__( s.istitle(
s.__class__( s.__rmul__( s.isupper(
s.__contains__( s.__setattr__( s.join(
s.__delattr__( s.__sizeof__( s.ljust(
s.__dir__( s.__str__( s.lower(
s.__doc__ s.__subclasshook__( s.lstrip(
s.__eq__( s.capitalize( s.maketrans(
s.__format__( s.casefold( s.partition(
s.__ge__( s.center( s.replace(
s.__getattribute__( s.count( s.rfind(
s.__getitem__( s.encode( s.rindex(
s.__getnewargs__( s.endswith( s.rjust(
s.__gt__( s.expandtabs( s.rpartition(
s.__hash__( s.find( s.rsplit(
s.__init__( s.format( s.rstrip(
s.__iter__( s.format_map( s.split(
s.__le__( s.index( s.splitlines(
s.__len__( s.isalnum( s.startswith(
s.__lt__( s.isalpha( s.strip(
s.__mod__( s.isdecimal( s.swapcase(
s.__mul__( s.isdigit( s.title(
s.__ne__( s.isidentifier( s.translate(
s.__new__( s.islower( s.upper(
s.__reduce__( s.isnumeric( s.zfill(
s.__reduce_ex__( s.isprintable(
s.__repr__( s.isspace(
该问题的所有方法都表示在这里,你不能确定这一方法并不存在。
在Python你可以拦截点呼吁通过 __getattr__
和 __getattribute__
, ,使得有可能创建方法",在运行时"
Exemple:
class MoreMethod(object):
def some_method(self, x):
return x
def __getattr__(self, *args):
return lambda x: x*2
如果你执行它,你可以拨打的方法不存在对象的字典...
>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10
这就是为什么你使用 更容易寻求宽恕而不是许可 范式蟒蛇。
最简单的方式获得的列表方法的任何目的使用 help()
命令。
%help(object)
它将列出所有可用/重要的方法与对象。
例如:
help(str)
一个可以创建一个 getAttrs
功能将返回的一个目的可调用的财产的名字
def getAttrs(object):
return filter(lambda m: callable(getattr(object, m)), dir(object))
print getAttrs('Foo bar'.split(' '))
那将会返回
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
有没有可靠的方式列出所有对象的方法。 dir(object)
通常是有用的,但在某些情况下,它可能不一一列举所有的方法。根据 dir()
文档: "有一个说法, 尝试 回一系列有效的属性,对象。"
检查方法存在可以通过 callable(getattr(object, method))
正如已经提到。
...有至少一个简单的方式来检查它是否有一个特定方法比简单地检查,如果发生错误的当方法被称为
虽然"更容易寻求宽恕而不是许可"肯定的Python的方式,你在找什么可能:
d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
d.get('foo')
# OUT: 'bar'
把清单作为一个对象
obj = []
list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))
你会得到:
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
为了寻找具体的方法在整个模块
for method in dir(module) :
if "keyword_of_methode" in method :
print(method, end="\n")