473,407 Members | 2,326 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Emulating Python Inheritance Manually

"""
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?
Jul 18 '05 #1
0 1245

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Nicolas Lehuen | last post by:
Hi, I hope this is not a FAQ, but I have trouble understanding the behaviour of the super() built-in function. I've read the excellent book 'Python in a Nutshell' which explains this built-in...
22
by: Matthew Louden | last post by:
I want to know why C# doesnt support multiple inheritance? But why we can inherit multiple interfaces instead? I know this is the rule, but I dont understand why. Can anyone give me some concrete...
5
by: Stephan Schaem | last post by:
How does one write an unmanaged function that perform this functionality? In short I want to turn off/on visual style in my app... Thanks, Stephan PS: two people have been looking for...
31
by: John W. Kennedy | last post by:
I quite understand about prototypes and not having classes as such, but I happen to have a problem involving blatant is-a relationships, such that inheritance is the bloody obvious way to go. I can...
27
by: Josh | last post by:
We have a program written in VB6 (over 100,000 lines of code and 230 UI screens) that we want to get out of VB and into a better language. The program is over 10 years old and has already been...
22
by: Francois | last post by:
I discovered Python a few months ago and soon decided to invest time in learning it well. While surfing the net for Python, I also saw the hype over Ruby and tried to find out more about it, before...
19
by: fyhuang | last post by:
Hello all, I've been wondering a lot about why Python handles classes and OOP the way it does. From what I understand, there is no concept of class encapsulation in Python, i.e. no such thing as...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.