The dir function

"""
List all the methods and attributes of an object.
Some of the attributes are instance attributes, some are class attributes.
"""

import sys
import date   #the date.py module we wrote

d = date.Date(12, 31, 2019)
dictionary = d.__dict__

for name in dir(d):    #attribute is a string
    attribute = getattr(d, name)
    c1 = "m" if callable(attribute) else " " #This attribute is a method.
    c2 = "v" if name in dictionary else " "  #This attribute is an instance attribute.
    print(f"{c1}{c2} {name}")

sys.exit(0)

The methods of the object d are marked with “m”. The instance attributes of the object d are marked with “v” (for “variable”). The class attribute (e.g., lengths) is not marked at all.

m  __class__
m  __delattr__
   __dict__
m  __dir__
   __doc__
m  __eq__
m  __format__
m  __ge__
m  __getattribute__
m  __gt__
m  __hash__
m  __init__
m  __init_subclass__
m  __le__
m  __lt__
   __module__
m  __ne__
m  __new__
m  __reduce__
m  __reduce_ex__
m  __repr__
m  __setattr__
m  __sizeof__
m  __str__
m  __subclasshook__
   __weakref__
 v day
m  dayOfYear
m  getDay
m  getMonth
m  getYear
   lengths
 v month
m  monthsInYear
m  nextDay
m  nextDays
 v year

Where did all the __ attributes come from?

The attributes whose names start and end with __ are inherited by class date.Date from its base class object. The argument of the dir function can be a data type that is a class, such as object.

for name in dir(object):
    print(name)
__class__
__delattr__
__dir__
__doc__
__eq__
__format__
__ge__
__getattribute__
__gt__
__hash__
__init__
__init_subclass__
__le__
__lt__
__ne__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__

List the attributes introduced in class date.Date

import sys
import date   #the date.py module we wrote

attributesOfObject = set(dir(object))
attributesOfDate = set(dir(date.Date))
newAttributes = attributesOfDate - attributesOfObject

for attribute in sorted(newAttributes):
    print(attribute)

sys.exit(0)
__dict__
__module__
__weakref__
dayOfYear
getDay
getMonth
getYear
lengths
monthsInYear
nextDay
nextDays