Emulating Python Inheritance Manually

Kamilche klachemin at home.com
Thu May 27 00:00:45 EDT 2004


"""
Emulating Python inheritance manually.

By loading it from disk at run time, you can create new custom types
without programmer intervention, and reload them on demand,
without breaking anything. The only time programmer intervention
is required, is when new functions are added.

It works well for data... I can use 'chicken.color' to access that
attribute, but not for functions. I can't say 'chicken.printme()',
I have to say 'chicken.do('printme') instead.
It can look up the function OK, but the 'chicken.print()' isn't
passing the 'self' argument to the function, which results in
one argument too few being sent to the function.
Does anyone have a way around this problem?
"""

import sys
import types

master = {}
masterbysortid = {}
functions = {}
__classctr = 0

# Unbound methods

def base_print(self, *args):
    print "# This is a base print function", self

def custom_print(self, *args):
    print "# Hey! Custom print function, unrelated to a class", self

def animal_print(self, *args):
    print "# This is the animal print function", self

def horse_print(self, *args):
    print "# This is the horse print function", self

def chicken_print(self, *args):
    print "# This is the chicken print function", self

def animal_speak(self, *args):
    print "# Generic animal speak:", text

def chicken_speak(self, **args):
    print "# Squawk!", args['text']


# Classes

class CreateObject:
    
    def __init__(self, args):
        ' Constructor'
        if args == None:
            raise 'Invalid type!'
        if type(args) != type({}):
            raise 'Invalid argument!'
        if not args.has_key('TYPE'):
            raise 'Missing type!'
        typename = args['TYPE']
        if not master.has_key(typename):
            raise 'Unknown type ' + typename + '!'
        self.__dict__.update(args)

    def do(self, event, **args):
        fn = getattr(self, event)
        if callable(fn):
            fn(self, **args)
        else:
            raise "Can't call '" + str(fn) + "'! Make sure it's
registered via RegisterFunctions!"

    def update(self, args):
        if args == None:
            raise 'Invalid type!'
        if type(args) != type({}):
            raise 'Invalid argument!'
        self.__dict__.update(args)

    def data(self):
        return self.__dict__
       
    def __str__(self):
        ' Return a printable version of the data'
        return str(self.__dict__)

    def printattrs(self, prefix):
        for key, value in self.__dict__.items():
            print prefix, key, value

    def __getattr__(self, name):
        ' Look for the data in the inherited type, if it doesnt
exist.'
        # Look for the data in the object instance
        m = self
        if m.__dict__.has_key(name):
            return m.__dict__[name]
        else:
            # Look for the data in the object class
            typename = m.__dict__['TYPE']
            m = master[typename]
            if m.__dict__.has_key(name):
                return m.__dict__[name]
            else:
                # Look for the object in the inherited class
                typename = m.__dict__['INHERITS']
                if typename == None:
                    raise AttributeError, name
                else:
                    m = master[typename]
                    if m.__dict__.has_key(name):
                        return m.__dict__[name]
                    else:
                        raise AttributeError, name

                    
 
def RegisterType(args):
    global master
    global __classctr
    
    # Ensure they passed in arguments
    if args == None:
        raise 'Invalid type!'
    
    # Ensure they passed in a dictionary
    if type(args) != type({}):
        raise 'Invalid argument!'
    
    # Ensure the dictionary included a 'TYPE' entry
    if not args.has_key('TYPE'):
        raise 'Missing type!'
    
    # Extract the type
    typename = args['TYPE']
    
    # Ensure the type doesn't already exist
    if master.has_key(typename):
        raise 'Type ' + typename + ' already exists!'

    if not args.has_key('INHERITS'):
        # Inherit from BASE, if no supertype specified
        if typename == 'BASE':
            inherits = None
        else:
            inherits = 'BASE'
        args['INHERITS'] = inherits
    else:     
        # Inherit from another type
        inherits = args['INHERITS']
        if not master.has_key(inherits):
            raise "Can't inherit from invalid type " + inherits + "!"

    # Replace function names with function pointers
    for (key, value) in args.items():
        if type(value) == type("") and functions.has_key(value):
            args[key] = functions[value]
            

    # Add it to the master
    master[typename] = None
    if not inherits:
        m = {}
    else:
        m = master[inherits].data()
    __classctr += 1
    m.update(args)
    c = CreateObject(m)
    c.__sortid = __classctr
    master[typename] = c
    masterbysortid[__classctr] = typename

def RegisterFunctions(args):
    if args == None:
        raise 'Invalid type!'
    if type(args) != type([0]):
        raise 'Invalid argument!'
    for f in args:
        name = f.__name__
        if functions.has_key(name):
            raise 'Function already exists!'
        functions[name] = f

# Testing
def Test():
    RegisterFunctions([animal_speak, base_print, animal_print,
horse_print, chicken_print, chicken_speak])

    RegisterType({'TYPE':       'BASE',             \
                  'NAME':       'Base Object',      \
                  'printme':    'base_print'})
    RegisterType({'TYPE':       'ANIMAL',           \
                  'NAME':       'Generic Animal',   \
                  'printme':    'animal_print',     \
                  'speak':      'animal_speak'})
    RegisterType({'TYPE':       'HORSE',            \
                  'INHERITS':   'ANIMAL',           \
                  'NAME':       'Horse',            \
                  'printme':    'horse_print'})
    RegisterType({'TYPE':       'CHICKEN',          \
                  'INHERITS':   'ANIMAL',           \
                  'name':       'Chicken',          \
                  'speak':      'chicken_speak',    \
                  'color':      'white',            \
                  'printme':    'chicken_print'})

    print '#\tFunctions:'
    for key, value in functions.items():
        print '#\t', key, '\t', value
        
    print '#\tMaster:'
    keys = masterbysortid.keys()
    keys.sort()
    for key in keys:
        k = masterbysortid[key]
        print '#\t', k
        value = master[k]
        value.printattrs('#\t\t')
    
    
    obj1 = CreateObject({'TYPE': 'BASE', 'x': 1, 'y': 2})
    obj2 = CreateObject({'TYPE': 'BASE', 'x': 1, 'y': 2, 'z': 3,
'printme': custom_print})
    chicken = CreateObject({'TYPE': 'CHICKEN', 'name': 'Chicken
Little'})

    print "# Chicken:", chicken
    print "# OK, let's see if this works now:"
    print "# Chicken color:", chicken.color
    chicken.do('speak', text = "I'm squawking here!")
    chicken.do('printme')
    # What I would like to do, is this:
    # chicken.printme()
    chicken.do('speak', text = "I would really like to say
'chicken.printme()' instead. Can I?")


# Startup routine
if __name__ == "__main__":
    Test()

# Sample output
#   Functions:
#   chicken_print   <function chicken_print at 0x01F005B8>
#   animal_speak    <function animal_speak at 0x00B687C0>
#   horse_print     <function horse_print at 0x01A15100>
#   base_print  <function base_print at 0x02000180>
#   animal_print    <function animal_print at 0x01FB61C8>
#   chicken_speak   <function chicken_speak at 0x01357558>
#   Master:
#   BASE
#       INHERITS BASE
#       __sortid 1
#       NAME Generic Animal
#       TYPE ANIMAL
#       printme <function animal_print at 0x01FB61C8>
#       speak <function animal_speak at 0x00B687C0>
#   ANIMAL
#       INHERITS ANIMAL
#       NAME Horse
#       color white
#       printme <function chicken_print at 0x01F005B8>
#       name Chicken
#       __sortid 2
#       TYPE CHICKEN
#       speak <function chicken_speak at 0x01357558>
#   HORSE
#       INHERITS ANIMAL
#       __sortid 3
#       NAME Horse
#       TYPE HORSE
#       printme <function horse_print at 0x01A15100>
#       speak <function animal_speak at 0x00B687C0>
#   CHICKEN
#       INHERITS ANIMAL
#       __sortid 4
#       NAME Horse
#       color white
#       TYPE CHICKEN
#       speak <function chicken_speak at 0x01357558>
#       printme <function chicken_print at 0x01F005B8>
#       name Chicken
# Chicken: {'TYPE': 'CHICKEN', 'name': 'Chicken Little'}
# OK, let's see if this works now:
# Chicken color: white
# Squawk! I'm squawking here!
# This is the chicken print function {'TYPE': 'CHICKEN', 'name':
'Chicken Little'}
# Squawk! I would really like to say 'chicken.printme()' instead. Can
I?



More information about the Python-list mailing list