簡體   English   中英

如何知道 Python object 中的屬性與方法?

[英]How to know attributes vs methods in Python object?

您如何知道 Python object 中的屬性與方法? 使用 dir 方法時,它只列出所有內容,例如 dir('string')。

您可以測試屬性的類型:

from types import MethodType
from pprint import pprint

class A(object):
  def __init__(self) -> None:
    self._field = 3
    self._callable_field = lambda x: x
  
  def my_method(self):
    pass

  @classmethod
  def my_static_method(cls):
    pass

  def __str__(self) -> str:
    return repr(self)

A.another_method = lambda self: None

a = A()
pprint([(d, type(getattr(a,d)) is MethodType) for d in dir(a)])

印刷

[('__class__', False),
 ('__delattr__', False),
 ('__dict__', False),
 ('__dir__', False),
 ('__doc__', False),
 ('__eq__', False),
 ('__format__', False),
 ('__ge__', False),
 ('__getattribute__', False),
 ('__gt__', False),
 ('__hash__', False),
 ('__init__', True),
 ('__init_subclass__', False),
 ('__le__', False),
 ('__lt__', False),
 ('__module__', False),
 ('__ne__', False),
 ('__new__', False),
 ('__reduce__', False),
 ('__reduce_ex__', False),
 ('__repr__', False),
 ('__setattr__', False),
 ('__sizeof__', False),
 ('__str__', True),              # <<<<<<<<<<
 ('__subclasshook__', False),
 ('__weakref__', False),
 ('_callable_field', False),     # <<<<<<<<<<
 ('_field', False),              # <<<<<<<<<<
 ('another_method', True),       # <<<<<<<<<<
 ('my_method', True),            # <<<<<<<<<<
 ('my_static_method', True)]     # <<<<<<<<<<

請注意,對於未在 class 定義中明確定義的內置方法(或稍后附加,請參閱上面的__str__another_method ),這不會打印True 另請注意,與對callable的測試不同,這實際上抓住了方法和可調用屬性之間的區別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM