给定任何类型的Python对象,是否有一种简单的方法可以获取此对象拥有的所有方法列表?
或者如果这不可能,是否至少有一种简单的方法可以检查它是否具有特定的方法,而不是在调用该方法时检查是否发生错误?
给定任何类型的Python对象,是否有一种简单的方法可以获取此对象拥有的所有方法列表?
或者如果这不可能,是否至少有一种简单的方法可以检查它是否具有特定的方法,而不是在调用该方法时检查是否发生错误?
对于许多对象,您可以使用此代码,将“object”替换为您感兴趣的对象:
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
AttributeError
,可以使用以下方法代替:
getattr()
不允许使用Pandas风格的Python 3.6抽象虚拟子类。此代码与上述代码相同,并忽略异常。import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
methodList = []
for method_name in dir(object):
try:
if callable(getattr(object, method_name)):
methodList.append(str(method_name))
except Exception:
methodList.append(str(method_name))
processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
for method in methodList:
try:
print(str(method.ljust(spacing)) + ' ' +
processFunc(str(getattr(object, method).__doc__)[0:90]))
except Exception:
print(method.ljust(spacing) + ' ' + ' getattr() failed')
get_methods(df['foo'])
print [method for method in dir(object) if callable(getattr(object, method))]
。 - OrienteerixAttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError'
错误。请参见https://dev59.com/ebHma4cB1Zd3GeqPSeIE获取详细信息。 - Karl Baker[ m for m in dir(object) if not m.startswith('__')]
- Johnprint(list(filter(lambda x: x[0] != '_' and callable(getattr(obj, x)), dir(obj))))
- Paulo Buchsbaumdir
不能可靠地获取对象的所有属性;最重要的是,一个类可以通过覆盖__dir__
来定义dir
返回的内容。 - chepner您可以使用内置的dir()
函数获取模块拥有的所有属性列表。在命令行中尝试一下,看看它是如何工作的。
>>> import moduleName
>>> dir(moduleName)
此外,您可以使用hasattr(module_name, "attr_name")
函数来查找模块是否具有特定属性。
有关更多信息,请参见Python内省。
dir(objectname)
。它会显示该对象可用的所有方法。我认为你想要类似这样的内容:
从一个对象中列出属性列表
内置函数dir()
可以完成这个任务。
摘自您Python shell上的help(dir)
输出:
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']
检查它是否具有特定的方法:
hasattr(object,"method")
if hasattr(obj, method) and callable(getattr(obj, method)):
- Bruno Bronosky获取任何对象的方法列表的最简单方法是使用help()
命令。
help(object)
它会列出与该对象相关的所有可用或重要方法。
例如:help(str)
假设我们有一个Python obj
。为了查看它具有的所有方法,包括那些被__
(magic methods)包围的方法:
print(dir(obj))
要排除魔法内置函数,可以这样做:
[m for m in dir(obj) if not m.startswith('__')]
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扩展、没有“binding”编译指令的Cython)。inspect.getmembers(self, predicate=inspect.ismethod)
? 检查 self
对象的成员,谓词为 inspect.ismethod
。 - hwjp打开Bash shell(在Ubuntu上按Ctrl + Alt + T)。在其中启动Python 3 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(
ipython
,开始键入对象并按 tab
键,它也可以工作。无需 readline 设置。 - Max Coplan