如何询问python对象的结构?

2024-04-25 09:56:47 发布

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

有没有一种方法可以通过编程确定一个对象的结构/模型,它的组成部分,如何迭代、操作、转换、分解和构建备份?你知道吗

试错是伟大的老师。我每天上他们的课。但在这里,我在寻找一种“更聪明地工作”或者至少是与众不同的方式。你知道吗

一点背景:我最近花了太多时间错误地处理pandasgroupby对象,因为我不了解它的构建块部分和类型。我没有正确处理迭代groupby对象时返回的元组。我现在对这个特定对象有了稍微好一点的理解,但还不够:例如,groupbyobj在迭代时分解为“params”和“table”。table又由indexrows组成。但我仍然不确定如何处理rows:它们是由什么组成的或分解成什么。This post包含重现问题的代码:请参阅原始文章底部的edit2。你知道吗

但这是一个特殊的情况;我的问题更一般。我的问题是,如果我还不知道python对象/类型的结构或“模型”,如何查询该对象以文本方式或图形方式显示这些信息?你知道吗


编辑:

出于探索和学习的目的,下面我尝试通过for循环在str对象上运行每个str方法。meth对象在循环的前两行中被正确地解释(例如,__add____class__),但是在我尝试运行obj.meth时被解释为meth。我怎样才能解决这个问题?你知道吗

输入:

obj = 'my_string'

object_methods = [method_name for method_name in dir(obj)
                  if callable(getattr(obj, method_name))]

print(len(object_methods))
print(object_methods)

输出:

77
['__add__', '__class__', . . ., 'upper', 'zfill']

输入:

for meth in object_methods:
    print(meth)
    try:
        print('obj.meth for obj', obj, 'and method', meth, ':') 
        obj.meth
    except AttributeError as e:
        print('obj.meth for obj', obj, 'and method', meth, ': AttributeError:', e)

输出:

__add__
obj.meth for obj my_string and method __add__ :
obj.meth for obj my_string and method __add__ : AttributeError: 'str' object has no attribute 'meth'
__class__
obj.meth for obj my_string and method __class__ :
obj.meth for obj my_string and method __class__ : AttributeError: 'str' object has no attribute 'meth'
. . .

Tags: and对象addobjforstringobjectmy
1条回答
网友
1楼 · 发布于 2024-04-25 09:56:47

可以使用__dict___dir查看对象模型。你知道吗

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

jack = Person('jack',23)
print(jack.__dict__)
print(dir(jack))

输出:

{'age': 23, 'name': 'jack'}
['__doc__', '__init__', '__module__', 'age', 'name']

相关问题 更多 >

    热门问题