Welcome, guest | Sign In | My Account | Store | Cart

The following function creates a map of all members of a class, navigating ALL of the base classes in the correct order. This can be used for various purposes, like checking whether a certain method is defined anywhere in a class hierarchy.

Python, 27 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def all_members(aClass):
    members = {}
    bases = list(aClass.__bases__)
    bases.reverse()
    for base in bases:
        members.update(all_members(base))
    members.update(vars(aClass))
    return members

class Eggs:
    eggs = 'eggs'
    spam = None

class Spam:
    spam = 'spam'

class Breakfast(Spam, Eggs):
    eggs = 'scrambled'

print all_members(Eggs)
print all_members(Spam)
print all_members(Breakfast)

# Output:
# {'spam': None, '__doc__': None, 'eggs': 'eggs', '__module__': '__main__'}
# {'spam': 'spam', '__doc__': None, '__module__': '__main__'}
# {'__doc__': None, 'eggs': 'scrambled', 'spam': 'spam', '__module__': '__main__'}
Created by Jürgen Hermann on Mon, 19 Mar 2001 (PSF)
Python recipes (4591)
Jürgen Hermann's recipes (14)
Python Cookbook Edition 1 (103)

Required Modules

  • (none specified)

Other Information and Tasks