dir函数python dir函数是什么意思

python语言中的内建函数dir()是干啥用的?。?/h2>dir() 函数
尽管查找和导入模块相对容易,但要记住每个模块包含什么却不是这么简单 。您并不希望总是必须查看源代码来找出答案 。幸运的是,Python 提供了一种方法,可以使用内置的 dir() 函数来检查模块(以及其它对象)的内容 。
dir() 函数可能是 Python 自省机制中最著名的部分了 。它返回传递给它的任何对象的属性名称经过排序的列表 。如果不指定对象,则 dir() 返回当前作用域中的名称
python中的“dir”和“help”作用是什么?dir和help是Python中两个强大的built-in函数,就像Linux的man一样 , 绝对是开发的好帮手 。比如查看list的所以属性:\x0d\x0adir(list)\x0d\x0a输出:\x0d\x0a['__add__','__class__','__contains__','__delattr__','__delitem__','__delslice__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getslice__','__gt__','__hash__','__iadd__','__imul__','__init__','__iter__','__le__','__len__','__lt__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__reversed__','__rmul__','__setattr__','__setitem__','__setslice__','__sizeof__','__str__','__subclasshook__','append','count','extend','index','insert','pop','remove','reverse','sort']\x0d\x0a然后查看list的pop方法的作用和用法:\x0d\x0ahelp(list.pop)\x0d\x0a输出:\x0d\x0aHelponmethod_descriptor:\x0d\x0apop(...)\x0d\x0aL.pop([index])-item--removeandreturnitematindex(defaultlast).\x0d\x0aRaisesIndexErroriflistisemptyorindexisoutofrange.\x0d\x0a(END)
python dir 和something 的class有什么关系没有something这个东西 。
Python下一切皆对象,每个对象都有多个属性(attribute) , python对属性有一套统一的管理方案 。
__dict__与dir()的区别:
dir()是一个函数 , 返回的是list;
__dict__是一个字典,键为属性名 , 值为属性值;
【dir函数python dir函数是什么意思】dir()用来寻找一个对象的所有属性,包括__dict__中的属性,__dict__是dir()的子集;
并不是所有对象都拥有__dict__属性 。许多内建类型就没有__dict__属性,如list,此时就需要用dir()来列出对象的所有属性 。
__dict__属性
__dict__是用来存储对象属性的一个字典,其键为属性名,值为属性的值 。
#!/usr/bin/python
# -*- coding: utf-8 -*-
class A(object):
class_var = 1
def __init__(self):
self.name = 'xy'
self.age = 2
@property
def num(self):
return self.age + 10
def fun(self):pass
def static_f():pass
def class_f(cls):pass
if __name__ == '__main__':#主程序
a = A()
print a.__dict__#{'age': 2, 'name': 'xy'}实例中的__dict__属性
print A.__dict__
'''
类A的__dict__属性
{
'__dict__': attribute '__dict__' of 'A' objects, #这里如果想深究的话查看参考链接5
'__module__': '__main__',#所处模块
'num': property object,#特性对象
'class_f': function class_f,#类方法
'static_f': function static_f,#静态方法
'class_var': 1, 'fun': function fun , #类变量
'__weakref__': attribute '__weakref__' of 'A' objects,
'__doc__': None,#class说明字符串
'__init__': function __init__ at 0x0000000003451AC8}
'''
a.level1 = 3
a.fun = lambda :x
print a.__dict__#{'level1': 3, 'age': 2, 'name': 'xy','fun': function lambda at 0x}
print A.__dict__#与上述结果相同
A.level2 = 4
print a.__dict__#{'level1': 3, 'age': 2, 'name': 'xy'}
print A.__dict__#增加了level2属性
print object.__dict__
'''
{'__setattr__': slot wrapper '__setattr__' of 'object' objects,
'__reduce_ex__': method '__reduce_ex__' of 'object' objects,
'__new__': built-in method __new__ of type object at,

推荐阅读