473,725 Members | 1,786 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.printm e()',
I have to say 'chicken.do('pr intme') 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(se lf, *args):
print "# Hey! Custom print function, unrelated to a class", self

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

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

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

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

def chicken_speak(s elf, **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('T YPE'):
raise 'Missing type!'
typename = args['TYPE']
if not master.has_key( typename):
raise 'Unknown type ' + typename + '!'
self.__dict__.u pdate(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 RegisterFunctio ns!"

def update(self, args):
if args == None:
raise 'Invalid type!'
if type(args) != type({}):
raise 'Invalid argument!'
self.__dict__.u pdate(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__.i tems():
print prefix, key, value

def __getattr__(sel f, 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(ar gs):
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('T YPE'):
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('I NHERITS'):
# 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_k ey(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 RegisterFunctio ns(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_k ey(name):
raise 'Function already exists!'
functions[name] = f

# Testing
def Test():
RegisterFunctio ns([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.printattr s('#\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('spe ak', text = "I'm squawking here!")
chicken.do('pri ntme')
# What I would like to do, is this:
# chicken.printme ()
chicken.do('spe ak', text = "I would really like to say
'chicken.printm e()' 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.printm e()' instead. Can
I?
Jul 18 '05 #1
0 1260

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

Similar topics

11
5033
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 function on pages 89-90. Based on the example on page 90, I wrote this test code : class A(object): def test(self): print 'A'
22
23379
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 examples?
5
2260
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 some time, and no solution aside putting the manifest in a file, and renaming the file before startup was found... very ugly hack ...
31
1937
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 think of several ad-hoc ways to achieve inheritance, but is there an accepted standard idiom? -- John W. Kennedy "But now is a new thing which is very old-- that the rich make themselves richer and not poorer, which is the true Gospel, for...
27
3785
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 ported from VB3 to VB6, a job which took over two years. We would like to port it to Python, but we need to continue to offer upgrades and fixes to the current VB6 version. Does anybody know of ways we could go about rewriting this, one screen at a...
22
2713
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 I definitely embarked on studying and practicing Python. I recently found two sufficient answers for choosing Python - which is a personal choice and others may differ, but I'd like to share it anyway : 1) In Ruby there is a risk of...
19
1412
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 a private variable. Any part of the code is allowed access to any variable in any class, and even non-existant variables can be accessed: they are simply created. I'm wondering what the philosophy behind this is, and if this behaviour is going...
0
8872
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8747
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9392
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
6694
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4505
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4773
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3211
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2619
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2150
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.