如何在Python3.9.5中递归地创建对象'dir()'?

如何在Python3.9.5中递归地创建对象'dir()'?,python,python-3.x,Python,Python 3.x,我知道这已经被问过很多次了,但我使用的是Python 3.9.5,我在这里找到的解决方案都不起作用 我的请求非常简单:获取对象及其子对象的所有可用对象的名称的XML树列表 为了说明这一点,我安装了许多Python模块,并希望了解模块提供的一切 dir() type()方法返回对象的类型,一些子对象本身有子对象,我需要一个XML树,列出最低级别对象的所有名称(仅名称,而不是值),即类型为int,bool,float,str,set,的对象,列表,元组,目录等 例如,我们考虑了一个名为“代码> Ob

我知道这已经被问过很多次了,但我使用的是Python 3.9.5,我在这里找到的解决方案都不起作用

我的请求非常简单:获取对象及其子对象的所有可用对象的名称的XML树列表

为了说明这一点,我安装了许多Python模块,并希望了解模块提供的一切

dir()

type()
方法返回对象的类型,一些子对象本身有子对象,我需要一个XML树,列出最低级别对象的所有名称(仅名称,而不是值),即类型为
int
bool
float
str
set
,的对象,
列表
元组
目录

例如,我们考虑了一个名为“代码> Obj/<代码>的对象,OBJ具有三个属性:<代码> A<代码>、<代码> B<代码>和<代码> C<代码>。code>a

没有唯一属性,
b
有两个唯一属性:
d
e
,而
d
e
没有唯一属性,
c
有三个唯一属性:
f
h
,而
f
有一个唯一属性,名为
i
g
具有名为
j
的唯一属性,
h
具有名为
k
的唯一属性
i
j
k
是内置类型

现在,结果应该如下所示:

<?xml version="1.0" ?>
<elem name='obj'>
    <attr name='a' />
    <elem name='obj.b'>
        <attr name='d' />
        <attr name='e' />
    </elem>
    <elem name='obj.c'>
        <elem name='obj.c.f'>
            <attr name='i' />
        </elem>
        <elem name='obj.c.g'>
            <attr name='j' />
        </elem>
        <elem name='obj.c.h'>
            <attr name='k' />
        </elem>
    </elem>
</elem>
dir(eval(f'{obj.__name__}.{attr}'))
但是
\uuu name\uuu
属性没有给出它的全名(比如
obj.c.f
),如果名称包含
\uuuu
,那么
\uu name\uu
值将没有
\uu
值。更不用说有些对象没有
\uuu name\uuu
属性

那么如何做到这一点呢


更新 我取得了一些初步的成功:

导入检查
从xml.dom.minidom导入文档
doc=文件()
def treeobj(对象,路径=“”):
fullname=f'{path}.{obj.\uuuuu name\uuuuuu}'.lstrip('.'))
node=doc.createElement('elem')
node.setAttribute('name',fullname)
对于目录中的属性(obj):
如果不是属性startswith(“”“”):
val=getattr(对象,属性)
如果检查isclass(val):
elem=treeobj(val,全名)
其他:
elem=doc.createElement('attr')
元素setAttribute('name',attr)
node.appendChild(elem)
返回节点
这是打印的输出(treeobj(os).toprettyxml()):

如何修复我的代码


getattr()函数访问PyQt6.QtCore.QAbstractEventDispatcher.TimerInfo对象的interval属性时,应该会生成错误,该对象是实例属性,getattr()不支持该属性,因此会生成错误


什么是实例属性以及如何获得“普通属性”和实例属性的值?

嗯,我刚刚修复了代码。它现在正在按预期工作。虽然它仍然是基本的,但它正在发挥作用

我想找到的是类属性,这些属性由同一个类的每个对象共享

类属性通常不会更改,也不应该更改,但如果更改,则会影响同一类的每个对象

实例属性对于每个对象都是唯一的,它们在
\uuuu init\uuuu
函数中声明,它们在创建对象时定义,并且它们在一个实例中的更改不会影响同一类的其他对象

getattr
只能获取类属性,因为类属性由同一类的所有对象共享,并且是预定义的,而实例属性对于每个对象都是唯一的,并且在对象创建之前没有定义

dir()
方法通常调用类的
\uuuu dir\uuuu()
方法,该方法以字符串形式返回类中属性的名称列表,这使得以编程方式使用其返回值访问类的属性有点困难

然而,大多数类都有一个
\uuuuu dict\uuuu
属性,这是类的一级属性字典,属性的名称以字符串形式作为键,就像
dir()
返回的内容一样,但是键有对相应对象的实际引用作为值,使得从键访问对象变得容易

代码如下:

导入导入库
进口检验
导入系统
从xml.dom.minidom导入文档
doc=文件()
def treeobj(对象,路径=“”):
fullname=f'{path}.{obj.\uuuuu name\uuuuuu}'.lstrip('.'))
节点=doc.createElement('类')
node.setAttribute('name',fullname)
对于对象中的属性。\uuuu dict\uuuuu.keys():
如果不是属性startswith(“”“”):
val=对象的属性
如果检查isclass(val):
elem=treeobj(val,全名)
其他:
elem=doc.createElement('attr')
元素setAttribute('name',attr)
node.appendChild(elem)
返回节点
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
obj=importlib.import\u模块(sys.argv[1])
附加文件(treeobj(obj))
打印(doc.toprettyxml())

不要使用eval,使用函数进行对象属性操作和代码/结构求值。提供具体的Python代码将更有助于构建生成XML输出的对象;我可以告诉您,它将提供您想要的
符号(通过
\uuuuuuu qualname\uuuuuuu
)。
<elem name="os">
        <elem name="os.DirEntry">
                <attr name="inode"/>
                <attr name="is_dir"/>
                <attr name="is_file"/>
                <attr name="is_symlink"/>
                <attr name="name"/>
                <attr name="path"/>
                <attr name="stat"/>
        </elem>
        <attr name="F_OK"/>
        <elem name="os.GenericAlias"/>
        <elem name="os.Mapping">
                <attr name="_abc_impl"/>
                <attr name="get"/>
                <attr name="items"/>
                <attr name="keys"/>
                <attr name="values"/>
        </elem>
        <elem name="os.MutableMapping">
                <attr name="_MutableMapping__marker"/>
                <attr name="_abc_impl"/>
                <attr name="clear"/>
                <attr name="get"/>
                <attr name="items"/>
                <attr name="keys"/>
                <attr name="pop"/>
                <attr name="popitem"/>
                <attr name="setdefault"/>
                <attr name="update"/>
                <attr name="values"/>
        </elem>
        <attr name="O_APPEND"/>
        <attr name="O_BINARY"/>
        <attr name="O_CREAT"/>
        <attr name="O_EXCL"/>
        <attr name="O_NOINHERIT"/>
        <attr name="O_RANDOM"/>
        <attr name="O_RDONLY"/>
        <attr name="O_RDWR"/>
        <attr name="O_SEQUENTIAL"/>
        <attr name="O_SHORT_LIVED"/>
        <attr name="O_TEMPORARY"/>
        <attr name="O_TEXT"/>
        <attr name="O_TRUNC"/>
        <attr name="O_WRONLY"/>
        <attr name="P_DETACH"/>
        <attr name="P_NOWAIT"/>
        <attr name="P_NOWAITO"/>
        <attr name="P_OVERLAY"/>
        <attr name="P_WAIT"/>
        <elem name="os.PathLike">
                <attr name="_abc_impl"/>
        </elem>
        <attr name="R_OK"/>
        <attr name="SEEK_CUR"/>
        <attr name="SEEK_END"/>
        <attr name="SEEK_SET"/>
        <attr name="TMP_MAX"/>
        <attr name="W_OK"/>
        <attr name="X_OK"/>
        <elem name="os._AddedDllDirectory">
                <attr name="close"/>
        </elem>
        <elem name="os._Environ">
                <attr name="_MutableMapping__marker"/>
                <attr name="_abc_impl"/>
                <attr name="clear"/>
                <attr name="copy"/>
                <attr name="get"/>
                <attr name="items"/>
                <attr name="keys"/>
                <attr name="pop"/>
                <attr name="popitem"/>
                <attr name="setdefault"/>
                <attr name="update"/>
                <attr name="values"/>
        </elem>
        <attr name="_check_methods"/>
        <attr name="_execvpe"/>
        <attr name="_exists"/>
        <attr name="_exit"/>
        <attr name="_fspath"/>
        <attr name="_get_exports_list"/>
        <attr name="_walk"/>
        <elem name="os._wrap_close">
                <attr name="close"/>
        </elem>
        <attr name="abc"/>
        <attr name="abort"/>
        <attr name="access"/>
        <attr name="add_dll_directory"/>
        <attr name="altsep"/>
        <attr name="chdir"/>
        <attr name="chmod"/>
        <attr name="close"/>
        <attr name="closerange"/>
        <attr name="cpu_count"/>
        <attr name="curdir"/>
        <attr name="defpath"/>
        <attr name="device_encoding"/>
        <attr name="devnull"/>
        <attr name="dup"/>
        <attr name="dup2"/>
        <attr name="environ"/>
        <elem name="os.OSError">
                <attr name="args"/>
                <attr name="characters_written"/>
                <attr name="errno"/>
                <attr name="filename"/>
                <attr name="filename2"/>
                <attr name="strerror"/>
                <attr name="winerror"/>
                <attr name="with_traceback"/>
        </elem>
        <attr name="execl"/>
        <attr name="execle"/>
        <attr name="execlp"/>
        <attr name="execlpe"/>
        <attr name="execv"/>
        <attr name="execve"/>
        <attr name="execvp"/>
        <attr name="execvpe"/>
        <attr name="extsep"/>
        <attr name="fdopen"/>
        <attr name="fsdecode"/>
        <attr name="fsencode"/>
        <attr name="fspath"/>
        <attr name="fstat"/>
        <attr name="fsync"/>
        <attr name="ftruncate"/>
        <attr name="get_exec_path"/>
        <attr name="get_handle_inheritable"/>
        <attr name="get_inheritable"/>
        <attr name="get_terminal_size"/>
        <attr name="getcwd"/>
        <attr name="getcwdb"/>
        <attr name="getenv"/>
        <attr name="getlogin"/>
        <attr name="getpid"/>
        <attr name="getppid"/>
        <attr name="isatty"/>
        <attr name="kill"/>
        <attr name="linesep"/>
        <attr name="link"/>
        <attr name="listdir"/>
        <attr name="lseek"/>
        <attr name="lstat"/>
        <attr name="makedirs"/>
        <attr name="mkdir"/>
        <attr name="name"/>
        <attr name="open"/>
        <attr name="pardir"/>
        <attr name="path"/>
        <attr name="pathsep"/>
        <attr name="pipe"/>
        <attr name="popen"/>
        <attr name="putenv"/>
        <attr name="read"/>
        <attr name="readlink"/>
        <attr name="remove"/>
        <attr name="removedirs"/>
        <attr name="rename"/>
        <attr name="renames"/>
        <attr name="replace"/>
        <attr name="rmdir"/>
        <attr name="scandir"/>
        <attr name="sep"/>
        <attr name="set_handle_inheritable"/>
        <attr name="set_inheritable"/>
        <attr name="spawnl"/>
        <attr name="spawnle"/>
        <attr name="spawnv"/>
        <attr name="spawnve"/>
        <attr name="st"/>
        <attr name="startfile"/>
        <attr name="stat"/>
        <elem name="os.stat_result">
                <attr name="count"/>
                <attr name="index"/>
                <attr name="n_fields"/>
                <attr name="n_sequence_fields"/>
                <attr name="n_unnamed_fields"/>
                <attr name="st_atime"/>
                <attr name="st_atime_ns"/>
                <attr name="st_ctime"/>
                <attr name="st_ctime_ns"/>
                <attr name="st_dev"/>
                <attr name="st_file_attributes"/>
                <attr name="st_gid"/>
                <attr name="st_ino"/>
                <attr name="st_mode"/>
                <attr name="st_mtime"/>
                <attr name="st_mtime_ns"/>
                <attr name="st_nlink"/>
                <attr name="st_reparse_tag"/>
                <attr name="st_size"/>
                <attr name="st_uid"/>
        </elem>
        <elem name="os.statvfs_result">
                <attr name="count"/>
                <attr name="f_bavail"/>
                <attr name="f_bfree"/>
                <attr name="f_blocks"/>
                <attr name="f_bsize"/>
                <attr name="f_favail"/>
                <attr name="f_ffree"/>
                <attr name="f_files"/>
                <attr name="f_flag"/>
                <attr name="f_frsize"/>
                <attr name="f_fsid"/>
                <attr name="f_namemax"/>
                <attr name="index"/>
                <attr name="n_fields"/>
                <attr name="n_sequence_fields"/>
                <attr name="n_unnamed_fields"/>
        </elem>
        <attr name="strerror"/>
        <attr name="supports_bytes_environ"/>
        <attr name="supports_dir_fd"/>
        <attr name="supports_effective_ids"/>
        <attr name="supports_fd"/>
        <attr name="supports_follow_symlinks"/>
        <attr name="symlink"/>
        <attr name="sys"/>
        <attr name="system"/>
        <elem name="os.terminal_size">
                <attr name="columns"/>
                <attr name="count"/>
                <attr name="index"/>
                <attr name="lines"/>
                <attr name="n_fields"/>
                <attr name="n_sequence_fields"/>
                <attr name="n_unnamed_fields"/>
        </elem>
        <attr name="times"/>
        <elem name="os.times_result">
                <attr name="children_system"/>
                <attr name="children_user"/>
                <attr name="count"/>
                <attr name="elapsed"/>
                <attr name="index"/>
                <attr name="n_fields"/>
                <attr name="n_sequence_fields"/>
                <attr name="n_unnamed_fields"/>
                <attr name="system"/>
                <attr name="user"/>
        </elem>
        <attr name="truncate"/>
        <attr name="umask"/>
        <elem name="os.uname_result">
                <attr name="count"/>
                <attr name="index"/>
                <attr name="machine"/>
                <attr name="n_fields"/>
                <attr name="n_sequence_fields"/>
                <attr name="n_unnamed_fields"/>
                <attr name="nodename"/>
                <attr name="release"/>
                <attr name="sysname"/>
                <attr name="version"/>
        </elem>
        <attr name="unlink"/>
        <attr name="unsetenv"/>
        <attr name="urandom"/>
        <attr name="utime"/>
        <attr name="waitpid"/>
        <attr name="waitstatus_to_exitcode"/>
        <attr name="walk"/>
        <attr name="write"/>
</elem>