如何在没有 __dict__ 的情况下列出 Python 对象的属性
通常你可以使用 __dir__ 列出 Python 对象的所有属性和函数:
namedtuple_dir_example.py
from collections import namedtuple
nt = namedtuple("Foo", [])
print(nt.__dict__) # 打印 nt 的属性和函数。这对于找出例如你可以在对象上调用哪些函数非常有用:
但是对于某些对象如 datetime.datetime,这不起作用。尝试运行
datetime_dict_fail.py
from datetime import datetime
dt = datetime.now()
print(dt.__dict__)将导致
error.txt
Traceback (most recent call last):
File "test.py", line 3, in <module>
AttributeError: 'datetime.datetime' object has no attribute '__dict__'那么你如何找出你的 datetime.datetime 对象有哪些属性以及你可以在其上调用什么函数?
使用 dir():
datetime_dir_example.py
from datetime import datetime
dt = datetime.now()
print(dir(dt))这将打印例如
datetime_dir_output.py
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow