【问题标题】:How to know attributes vs methods in Python object?如何知道 Python 对象中的属性和方法?
【发布时间】:2020-11-16 18:34:58
【问题描述】:

您如何知道 Python 对象中的属性与方法?使用 dir 方法时,它只列出所有内容,例如 dir('string')。

【问题讨论】:

  • 这两个链接的问题都没有回答 OP 的问题。他们问的是如何测试方法和属性之间的区别,而不是它们是什么或如何获得完整列表。
  • 你能澄清一下你到底想要做什么吗? (如果可能,到目前为止您还做了什么?)您实际上是在寻找方法,还是只是在寻找 any 可调用的属性?你对 any 方法感兴趣,还是对 classmethods/staticmethods 不感兴趣?您是否有理由需要以编程方式找出这一点,而不是查阅帮助/文档?

标签: python python-3.x


【解决方案1】:

你可以测试属性的类型:

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)]     # <<<<<<<<<<

请注意,对于未在类定义中明确定义的内置方法(或稍后附加,请参阅上面的 __str__another_method),这不会打印 True。另请注意,与测试 callable 不同,这实际上抓住了方法和可调用属性之间的区别。

【讨论】:

  • "请注意,这仅对类定义中明确定义的属性打印 True" 不正确,请考虑,A.another_method = lambda self: None
  • @juanpa.arrivillaga 好点。我想说的是,内置方法不会被标记为这样,只有那些明确的defined(例如__init__)被标记为True。不知道如何用不同的方式表达。
  • @juanpa.arrivillaga 试图改写它,但不确定它是否更清晰
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2021-05-19
  • 2023-01-07
相关资源
最近更新 更多