有没有一种方法可以通过编程确定一个对象的结构/模型,它的组成部分,如何迭代、操作、转换、分解和构建备份?你知道吗
试错是伟大的老师。我每天上他们的课。但在这里,我在寻找一种“更聪明地工作”或者至少是与众不同的方式。你知道吗
一点背景:我最近花了太多时间错误地处理pandasgroupby
对象,因为我不了解它的构建块部分和类型。我没有正确处理迭代groupby
对象时返回的元组。我现在对这个特定对象有了稍微好一点的理解,但还不够:例如,groupby
obj在迭代时分解为“params
”和“table
”。table
又由index
和rows
组成。但我仍然不确定如何处理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'
. . .
可以使用__dict___和dir查看对象模型。你知道吗
输出:
相关问题 更多 >
编程相关推荐