Python查看模块中的属性
内置函数dir可用于列出某模块中定义了哪些属性(全局名称空间)。完整的说明见help(dir)。
importb
dir(b)
输出结果:
['__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__','f','g','x','y','z']
可见,模块的属性中除了自己定义的属性外,还有一些内置的属性,比如上面以__开头和结尾的属性。
如果dir()不给任何参数,则输出当前环境下定义的名称属性:
>>>importb
>>>x=3
>>>aaa=333
>>>dir()
['__annotations__','__builtins__','__doc__','__loader__','__name__','__package__','__spec__','aaa','b','x']
每个属性都对应一个对象,例如x对应的是int对象,b对应的是module对象:
>>>type(x)
>>>type(b
既然是对象,那么它们都会有自己的属性。例如:
>>>dir(x)
['__abs__','__add__','__and__','__bool__','__ceil__','__class__','__delattr__','__dir__','__divmod__','__doc__','__eq__','__float__','__floor__','__floordiv__','__format__','__ge__','__getattribute__','__getnewargs__','__gt__','__hash__','__index__','__init__','__init_subclass__','__int__','__invert__','__le__','__lshift__','__lt__','__mod__','__mul__','__ne__','__neg__','__new__','__or__','__pos__','__pow__','__radd__','__rand__','__rdivmod__','__reduce__','__reduce_ex__','__repr__','__rfloordiv__','__rlshift__','__rmod__','__rmul__','__ror__','__round__','__rpow__','__rrshift__','__rshift__','__rsub__','__rtruediv__','__rxor__','__setattr__','__sizeof__','__str__','__sub__','__subclasshook__','__truediv__','__trunc__','__xor__','bit_length','conjugate','denominator','from_bytes','imag','numerator','real','to_bytes']
所以,也可以直接dir某个模块内的属性:
importb
dir(b.x)
dir(b.__name__)
dir()不会列出内置的函数和变量,如果想要输出内置的函数和变量,可以去标准模块builtins中查看,因为它们定义在此模块中:
importbuiltins
dir(buildins)
除了内置dir()函数可以获取属性列表(名称空间),对象的__dict__属性也可以获取对象的属性字典(名称空间),它们的结果不完全一样。详细说明参见dir()和__dict__属性区别。
总的来说,获取对象M中一个自定义的属性age,有以下几种方法:
M.age
M.__dict__['age']
sys.modules['M'].age
getattr(M,'age')
以上内容为大家介绍了Python查看模块中的属性,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python字符串和Java字符串
接下来,又到了Python字符串与Java字符串PK的时刻。Java中有比较字符串的方法,即compareTo()方法与equals()方法,前一个方法逐一比较两个字符...详情>>
2023-11-05 21:58:02
用Python开发一个简单的猜数字游戏
本文介绍如何使用Python制作一个简单的猜数字游戏。游戏规则玩家将猜测一个数字。如果猜测是正确的,玩家赢。如果不正确,程序会提示玩家所猜的...详情>>
2023-11-05 21:40:12
跟踪数据的Python技巧
了解如何运用Python的某些数据对象,有利于保持井然有序的状态,避免在处理数据科学项目中的大量数据时出错。在数据科学项目中,有时想跟踪数据...详情>>
2023-11-05 20:37:09
Python之描述符
Descriptors(描述符)是Python语言中一个深奥但很重要的一个黑魔法,它被广泛应用于Python语言的内核,熟练掌握描述符将会为Python程序员的工具...详情>>
2023-11-05 18:48:43