Attribute eines Python-Objekts ohne __dict__ auflisten
English
Deutsch
Normalerweise kannst du alle Attribute und Funktionen eines Python-Objekts mit __dir__ auflisten:
namedtuple_dir_example.py
from collections import namedtuple
nt = namedtuple("Foo", [])
print(nt.__dict__) # Gibt Attribute und Funktionen von nt aus.Dies kann sehr nützlich sein, um herauszufinden, z.B. welche Funktionen du auf einem Objekt aufrufen kannst:
Für einige Objekte wie datetime.datetime funktioniert dies jedoch nicht. Der Versuch, auszuführen
datetime_dict_fail.py
from datetime import datetime
dt = datetime.now()
print(dt.__dict__)wird zu folgendem führen
error.txt
Traceback (most recent call last):
File "test.py", line 3, in <module>
AttributeError: 'datetime.datetime' object has no attribute '__dict__'Wie kannst du also herausfinden, welche Attribute dein datetime.datetime-Objekt hat und welche Funktionen du darauf aufrufen kannst?
Verwende dir():
datetime_dir_example.py
from datetime import datetime
dt = datetime.now()
print(dir(dt))Dies wird z.B. ausgeben
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