Tho*_*zer 379 python introspection
给定一个任何类型的Python对象,是否有一种简单的方法来获取该对象具有的所有方法的列表?
要么,
如果这是不可能的,至少有一种简单的方法来检查它是否有一个特定的方法,而不仅仅是检查方法被调用时是否发生错误?
ljs*_*ljs 475
您似乎可以使用此代码,将"对象"替换为您感兴趣的对象:
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
Run Code Online (Sandbox Code Playgroud)
我在这个网站上发现了它.希望,这应该提供一些进一步的细节!
Bil*_*ard 201
您可以使用内置dir()函数来获取模块具有的所有属性的列表.在命令行中尝试此操作以查看其工作原理.
>>> import moduleName
>>> dir(moduleName)
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用该hasattr(module_name, "attr_name")函数来确定模块是否具有特定属性.
有关更多信息,请参阅Python内省指南.
Paw*_*mar 77
最简单的方法是使用dir(objectname).它将显示该对象可用的所有方法.很酷的把戏.
小智 31
要检查它是否有特定的方法:
hasattr(object,"method")
Run Code Online (Sandbox Code Playgroud)
iva*_*ncz 27
我相信你想要的是这样的:
来自对象的属性列表
在我看来,内置函数dir()可以为您完成这项工作.取自help(dir)Python Shell上的输出:
目录(...)
Run Code Online (Sandbox Code Playgroud)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']
Run Code Online (Sandbox Code Playgroud)
当我检查你的问题时,我决定展示我的思路,更好地格式化输出dir().
dir_attributes.py(Python 2.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
Run Code Online (Sandbox Code Playgroud)
dir_attributes.py(Python 3.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("")
Run Code Online (Sandbox Code Playgroud)
希望我贡献:).
jma*_*g2k 23
除了更直接的答案之外,如果我没有提及iPython,我将会失职.点击"标签"以查看可用的方法,并使用自动完成功能.
一旦找到方法,请尝试:
help(object.method)
Run Code Online (Sandbox Code Playgroud)
查看pydocs,方法签名等
啊...... REPL.
Ser*_*nov 13
假设我们有一个 Python obj。然后查看它拥有的所有方法,包括那些被__(魔法方法)包围的方法:
print(dir(obj))
Run Code Online (Sandbox Code Playgroud)
要仅查看通过中缀(点)表示法可用的方法,可以:
[m for m in dir(obj) if not m.startswith('__')]
Run Code Online (Sandbox Code Playgroud)
pau*_*kow 12
如果您特别需要方法,则应使用inspect.ismethod.
对于方法名称:
import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]
Run Code Online (Sandbox Code Playgroud)
对于方法本身:
import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]
Run Code Online (Sandbox Code Playgroud)
有时候inspect.isroutine也很有用(对于内置插件,C扩展,没有"绑定"编译器指令的Cython).
Val*_*sik 11
打开bash shell(在Ubuntu上按ctrl + alt + T).在其中启动python3 shell.创建对象来观察方法.只需在其后添加一个点并按两次"tab"即可看到类似的内容:
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(
Run Code Online (Sandbox Code Playgroud)
小智 7
这里指出的所有方法的问题是您不能确定方法不存在.
在Python可以拦截点主叫通__getattr__和__getattribute__,从而能够创建方法"在运行时"
例:
class MoreMethod(object):
def some_method(self, x):
return x
def __getattr__(self, *args):
return lambda x: x*2
Run Code Online (Sandbox Code Playgroud)
如果执行它,可以调用对象字典中不存在的方法...
>>> 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
Run Code Online (Sandbox Code Playgroud)
这就是为什么你使用Easier来请求宽恕而不是 Python中的权限范例.
小智 6
获取任何对象的方法列表的最简单方法是使用help()命令.
%help(object)
Run Code Online (Sandbox Code Playgroud)
它将列出与该对象关联的所有可用/重要方法.
例如:
help(str)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
321089 次 |
| 最近记录: |