1
help(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.

dir組み込み関数のヘルプファイルに問題がある可能性があります。例:

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']

1.dir()オブジェクトのメソッドを一覧表示できます。属性だけでなく
updatePhoneisメソッドであり、属性ではありません。

2.dir()の出力のメソッドである属性を知るにはどうすればよいですか?

4

4 に答える 4

2
  1. メソッドPythonの属性です。

  2. それらのさまざまな属性を確認してください。メソッドにはim_*属性があります。

于 2013-01-25T01:28:46.233 に答える
2

違いがわかると思いますが、メソッド属性なので、確認するしか方法はありません。

これがあなたのためにそれを分解する関数です:

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.getmembers呼び出し可能なメンバーを取得するための優れたショートカットがあります。

from inspect import getmembers
getmembers(obj, callable)

しかし、それ自身の述語に注意してください!Pythonで実装されたメソッドinspect.ismethod専用になります。多くのコアオブジェクトのメソッド(たとえば)は、その基準を満たしていません。True[].sort

于 2013-01-25T02:01:44.300 に答える
1

ヘルプファイルは正しいです。Pythonでは、メソッドは他の属性とまったく同じ方法でクラス(およびそれらのクラスのインスタンス)にアタッチされます。単純な属性を呼び出し可能な属性と区別するには、それを逆参照する必要があります。

>>> type(AddrBookEntry('tom','123').phone)
<type 'str'>
>>> type(AddrBookEntry('tom','123').updatePhone)
<type 'instancemethod'>
于 2013-01-25T01:38:43.027 に答える
-1

オブジェクトの属性を知りたい場合は、その属性を使用して__dict__ください。例えば:

>>> entry = AddrBookEntry('tom','123')
>>> entry.__dict__
{'name': 'tom', 'phone': '123'}

dir()デバッグを目的としています。本番コードでそれを使用することはおそらく悪い考えです。それが返すものは正確には明確に定義されていません。

于 2013-01-25T02:01:14.677 に答える