简体   繁体   English

如何在Python中使用变量打印(dir(module))?

[英]How to print(dir(module)) using a variable in Python?

import PyQt5
from PyQt5.QtWidgets import *

print(dir(PyQt5.QtWidgets))

That above code runs perfectly. 上面的代码运行完美。 But when I use a variable it gives an error. 但是,当我使用变量时,会出现错误。

qw="QtWidgets"
print(dir(PyQt5.qw))

AttributeError: module 'PyQt5' has no attribute 'qw' . AttributeError:模块'PyQt5'没有属性'qw' Is there anyway I can do that? 反正我能做到吗? The reason I use variable is because I want a user input to choose what modules to print(dir()). 我使用变量的原因是因为我希望用户输入选择要打印的模块(dir())。

The getattr built-in function will let you look up an attribute by name: 内置的getattr函数可让您按名称查找属性:

qw = "QtWidgets"
print(dir(getattr(PyQt5, qw)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM