python中的dir函数

python中的dir函数,python,Python,我发现dir内置函数的帮助文件中可能有问题。例如: dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of

我发现dir内置函数的帮助文件中可能有问题。例如:

dir([object]) -> list of strings        
If called without an argument, return the names in the current scope.  
Else, return an alphabetized list of names comprising (some of) the attributes  
of the given object, and of attributes reachable from it.  
If the object supplies a method named __dir__, it will be used; otherwise  
the default dir() logic is used and returns:  
  for a module object: the module's attributes.  
  for a class object:  its attributes, and recursively the attributes  
    of its bases.  
  for any other object: its attributes, its class's attributes, and  
    recursively the attributes of its class's base classes.
1.
dir()
可以列出对象的方法,而不仅仅是属性
updatePhone
是方法,而不是属性

2.我如何知道哪个是属性,哪个是dir()输出中的方法

  • 方法是Python中的属性

  • 检查它们的各种属性。方法具有
    im.*
    属性

  • 方法是Python中的属性

  • 检查它们的各种属性。方法具有
    im.*
    属性


  • 帮助文件是正确的。在Python中,方法以与任何其他属性完全相同的方式附加到类(以及这些类的实例)。为了区分简单属性和可调用属性,必须取消对其的引用:

    class  AddrBookEntry(object):
       'address book entry class'
       def __init__(self,nm,ph):
         self.name=nm
         self.phone=ph
       def updatePhone(self,newph):
         self.phone=newph
         print 'Updated phone # for :' ,self.name
    
    dir(AddrBookEntry('tom','123'))
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'phone', 'updatePhone']
    
    >>类型(AddrBookEntry('tom','123')。电话)
    >>>类型(AddrBookEntry('tom','123')。updatePhone)
    
    帮助文件是正确的。在Python中,方法以与任何其他属性完全相同的方式附加到类(以及这些类的实例)。为了区分简单属性和可调用属性,必须取消对其的引用:

    class  AddrBookEntry(object):
       'address book entry class'
       def __init__(self,nm,ph):
         self.name=nm
         self.phone=ph
       def updatePhone(self,newph):
         self.phone=newph
         print 'Updated phone # for :' ,self.name
    
    dir(AddrBookEntry('tom','123'))
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'phone', 'updatePhone']
    
    >>类型(AddrBookEntry('tom','123')。电话)
    >>>类型(AddrBookEntry('tom','123')。updatePhone)
    
    如果您想知道对象的属性,请使用
    \uuu dict\uuu
    属性。例如:

    >>> type(AddrBookEntry('tom','123').phone)
    <type 'str'>
    >>> type(AddrBookEntry('tom','123').updatePhone)
    <type 'instancemethod'>
    

    dir()
    用于调试。在生产代码中使用它可能是个坏主意。它返回的确切内容没有很好的定义。

    如果您想知道对象的属性,请使用
    \uuu dict\uuu
    属性。例如:

    >>> type(AddrBookEntry('tom','123').phone)
    <type 'str'>
    >>> type(AddrBookEntry('tom','123').updatePhone)
    <type 'instancemethod'>
    

    dir()
    用于调试。在生产代码中使用它可能是个坏主意。确切地说,它返回的内容并没有很好的定义。

    您可能会感觉到区别,但是方法是属性,所以唯一确定的方法是检查

    这里有一个函数可以为您分解它:

    >>> entry = AddrBookEntry('tom','123')
    >>> entry.__dict__
    {'name': 'tom', 'phone': '123'}
    
    inspect.getmembers
    有一个很好的获取可调用成员的快捷方式:

    def dirf(obj=None):
        """Get the output of dir() as a tuple of lists of callables and non-callables."""
        d = ([],[])
        for name in dir(obj):
            if callable(getattr(obj, name, locals().get(name))):
                d[0].append(name)
            else:
                d[1].append(name)
        return d
    

    但是要小心它自己的谓词
    inspect.ismethod
    对于在Python中实现的方法将仅为
    True
    。许多核心对象的方法(例如,
    [].sort
    )都不符合这一标准。

    你会感觉到区别,但方法是属性,所以唯一能真正确定的方法是检查

    这里有一个函数可以为您分解它:

    >>> entry = AddrBookEntry('tom','123')
    >>> entry.__dict__
    {'name': 'tom', 'phone': '123'}
    
    inspect.getmembers
    有一个很好的获取可调用成员的快捷方式:

    def dirf(obj=None):
        """Get the output of dir() as a tuple of lists of callables and non-callables."""
        d = ([],[])
        for name in dir(obj):
            if callable(getattr(obj, name, locals().get(name))):
                d[0].append(name)
            else:
                d[1].append(name)
        return d
    

    但是要小心它自己的谓词
    inspect.ismethod
    对于在Python中实现的方法将仅为
    True
    。许多核心对象的方法(例如,
    [].sort
    )不符合该标准。

    此处的预期输出是什么?此处的预期输出是什么?或2
    [name for name in dir(whatever)if callable(getattr(whatever,name))]
    callable()
    是不可靠的,因为函数在Python中是一级对象,但不是方法。我想您谈论的是实现
    \uuu call\uu
    的对象。虽然这种情况并不罕见,但我仍然认为我所说的是OP所寻求的合理近似值。按repr()中的
    'method'进行过滤
    检查.ismethod
    同样不可靠。或2
    [name for name in dir(whatever)if callable(getattr(whatever,name))]
    callable()
    是不可靠的,因为函数在Python中是一级对象,但不是方法。我想您谈论的是实现
    \uuu call\uu
    的对象。虽然这种情况并不罕见,但我仍然认为我所说的是OP所寻求的合理近似值。通过repr()中的
    'method'或
    inspect.ismethod
    进行过滤同样不可靠。-1 dict有键和值。属性是另一种东西,所有对象都有属性,不管它们是否实现
    \uuuuu dict\uuuuu
    @kojori:基本上,对象实现了getattribute和setattribute方法,这些方法在访问属性时被调用。Python对象模型没有属性的概念,它们是在更高的级别上实现的。如果您创建的类继承自
    对象
    ,则该类的实例(以及类对象)将具有属性,并且这些属性将存储在
    \uuuuuuuuuuu dict\uuuuuu
    中。我明白您的意思,以及您为什么这么说,但OP特别询问了
    目录
    ,你的回答并不能解释
    dir(obj)
    obj.\uuu dict\uuu
    之间的区别。也就是说,我会删除我的否决票,但我需要你在我可以修改答案之前编辑答案。-1 Dicts有键和值。属性是另一种东西,所有对象都有属性,不管它们是否实现
    \uuuuu dict\uuuuu
    @kojori:基本上,对象实现了getattribute和setattribute方法,这些方法在访问属性时被调用。Python对象模型没有属性的概念,它们是在更高的级别上实现的。如果您创建的类继承自
    对象
    ,则该类的实例(以及类对象)将具有属性,并且这些属性将存储在
    \uuuuuuuuuuu dict\uuuuuu
    中。我明白您的意思,以及您为什么这么说,但OP特别询问了
    目录
    ,你的回答并不能解释
    dir(obj)
    obj.\uuu dict\uuu
    之间的区别。这就是说,我会删除我的否决票,但我需要你在我可以之前编辑答案。