Python,列出参数的属性

2024-05-31 12:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题可能有点生疏。你知道吗

在下面的示例中,我试图从“message”参数中找出attribtue的列表。你知道吗

@respond_to("^meow")
def remind_me_at(self, message):
    fre = "asd: %s " % str(message.sender)
    fre = "asd: %s " % str(message.mention_name)
    fren = "asd: %s " % str(message.sender.name)
    #fren = "hello, %s!" % str(message)
    self.say(fren, message=message)
    self.say(fre, message=message)

由于没有文档,但代码是开源的,因此如何找到有效实现方法的文件;即使类位于库文件中。你知道吗

[[更新]] 我在另一个以不同方式问问题的帖子上找到了这个解决方案

[(name,type(getattr(math,name))) for name in dir(math)]

Tags: 文件nameself示例message参数mathsender
3条回答

正如Rob所指出的,dir命令能够列出属性。当您尝试调试正在运行的代码时,这非常方便。你知道吗

如果您可以使用代码进行交互式会话(您知道,只需运行ol'REPL解释器),请尝试:

>>> help(message)

如果该库的开发人员是一个不错的人,那么希望他们已经编写了一个值得一试的docstring,它将为您提供一些关于对象的上下文。你知道吗

另一个方便的工具是文件属性,但这只适用于模块。 因此,如果您知道要获取message的导入文件的名称,可以执行以下操作:

>>> import some_module   # `message` comes from this module
>>> some_module.__file__
/usr/lib/python/python35/lib/site-packages/some_module/__init__.py

一旦你知道了目录,就开始搜索message的源代码:

$ cd /usr/lib/python/python35/lib/site-packages/some_module
$ grep -r message *

使用dir()内置函数。它返回一个对象的所有属性的列表。你知道吗

print dir(message)

目录

dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the 
attributes of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; 
otherwise the default dir() logic is used and returns:

for a module object: the module's attributes.
for a class object:  its attributes, and recursively the attributes
  of its bases.
for any other object: its attributes, its class's attributes, and
  recursively the attributes of its class's base classes.

请定义一个名为TestClass的演示类,如下所示。你知道吗

>>> class TestClass(object):
...     def abc(self):
...         print('Hello ABC !')
...
...     def xyz(self):
...         print('Hello xyz !')
...
>>> dir(TestClass)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'abc', 'xyz']

获取属性

getattr(object, name[, default]) -> value

Get a named attribute from an object;

getattr可以从TestClass获取属性:

>>> getattr(TestClass, 'abc')
<unbound method TestClass.abc>

>>> getattr(TestClass, 'xxx', 'Invalid-attr')
'Invalid-attr'

哈萨特

hasattr(object, name) -> bool

Return whether the object has an attribute with the given name.

演示:

>>> hasattr(TestClass, 'abc')
True
>>> hasattr(TestClass, 'xxx')
False

如果什么也帮不了你,请把你的想法说清楚。你知道吗

相关问题 更多 >