0

I create an object of class datetime.date - d. And I want to get variables of class object d. I use dict for it. This attribute work in simple code:

class Simple:
    def __init__(self, name, age):
        self.name = name
        self.age = age


a = Simple("Bob", 30)
print(a.__dict__)

{'name': 'Bob', 'age': 30}

But it doesn't work with class datetime.date. Why? datetime.date - this is also a class, like Simple.

d = datetime.date(2020, 5, 11)
print(d.__dict__)

AttributeError: 'datetime.date' object has no attribute 'dict'

  • Not all classes have a `__dict__` attribute, e.g. those written in C or those with `__slots__`. Have you tried using `dir(d)` instead? – L3viathan May 29 '20 at 06:52
  • Not all objects carry a `__dict__`. For example, user-defined classes that define a `__slots__`. – juanpa.arrivillaga May 29 '20 at 06:52
  • datetime.date is implemented in C and that's why it doesn't have the `__dict__` attribute. – HNMN3 May 29 '20 at 06:54
  • To get something similar to what you were doing, but with `dir`, try something like `{k: getattr(d, k) for k in dir(d) if not k.startswith('_') and not callable(getattr(d, k))}` – L3viathan May 29 '20 at 06:56

0 Answers0