473,394 Members | 1,718 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,394 software developers and data experts.

Object-based inheritance in Python

Hi!

I'm looking for suggestions on object-based inheritance
in Python. Automatic forwarding (often called delegation)
in Python is easy:

def __getattr__(self, attr):
return getattr(self.delegatee, attr)
def __setattr__(self, attr, value):
return setattr(self.delegatee, attr, value)

Maybe there is a way to hand over self to the delegatee object.
So the next call on self in the delegatee object is send to the child
object.

A small example:

class Child:
def __init__(self, delegatee):
self.__dict__['delegatee'] = delegatee

# TODO ... delegation/overriding mechanism ....

def m(self):
self.m2(self)
def m3(self):
print("Child")

class Delegatee:
def m2(self):
self.m3(self)
def m3(self):
print("Child")

#_______________________
c = Child(Delegatee())
c.m() Child


The call to m2() is forwarded to the Delegatee.
The call to m3() in m2() is redirected to Child and
the m3() Method in Child is called:
================================================== ===
m2(child_self)
child --------------------> delegatee
|
<-------------------|
m3(child_self)
================================================== ===

This functionality would be helpfull in Patterns (Decorator, Strategy, etc.)

Do you have any suggestions on how to hand over self to the delegatee?
Since the first argument of every method in Python is self, the rest of
the object-based inheritance works automatically!

I usually work with Java, where I implemented this functionality with
enormous effort. When I saw Pythons reflective capabilities (__getattr__
etc.) I wondered if this is possible in an generic/easy way.
Thanks in advance
Tobias

Jul 18 '05 #1
5 1662
Tobias Windeln wrote:
Hi!

I'm looking for suggestions on object-based inheritance
in Python. Automatic forwarding (often called delegation)
in Python is easy:


Have a look at Hans Nowaks 'selfish' implementation:
http://zephyrfalcon.org/download/selfish-0.4.2.zip

This is a pythonesque interpretation of the 'self' language by Sun.
By the way, if you are googling, you want probably look for 'prototype based
languages'.
Jul 18 '05 #2
Tobias Windeln <To************@gmx.de> writes:
Maybe there is a way to hand over self to the delegatee object. [...]
class Child:
def __init__(self, delegatee):
self.__dict__['delegatee'] = delegatee


Can't you just use this pattern:

self.__dict__['delegatee'] = delegatee(self)
?

'as
Jul 18 '05 #3
Stephan Diehl wrote:
Tobias Windeln wrote:

Hi!

I'm looking for suggestions on object-based inheritance
in Python. Automatic forwarding (often called delegation)
in Python is easy:

Have a look at Hans Nowaks 'selfish' implementation:
http://zephyrfalcon.org/download/selfish-0.4.2.zip


Thanks, this was exactly what I was looking for.

Jul 18 '05 #4
Alexander Schmolck wrote:
Tobias Windeln <To************@gmx.de> writes:

Maybe there is a way to hand over self to the delegatee object.


[...]

class Child:
def __init__(self, delegatee):
self.__dict__['delegatee'] = delegatee

Can't you just use this pattern:

self.__dict__['delegatee'] = delegatee(self)


This results in:
AttributeError: Delegatee instance has no __call__ method
Here is the solution by Hans Nowaks
(http://zephyrfalcon.org/download/selfish-0.4.2.zip):

################################################## ################

import new
import types

__version__ = "0.4.2"
__author__ = "Hans Nowak"
__license__ = "python"
__cvsid__ = "$Id: selfish_v2.py,v 1.3 2003/09/22 04:30:50 hansn Exp $"

def rebind(method, obj):
return new.instancemethod(method.im_func, obj, obj.__class__)

class SelfObject:

def __init__(self):
pass

def __setattr__(self, name, value):
if name.endswith("_p"):
assert isinstance(value, SelfObject), \
"Only SelfObjects can be used for inheritance"
if isinstance(value, types.FunctionType):
m = new.instancemethod(value, self, self.__class__)
self.__dict__[name] = m
elif isinstance(value, types.UnboundMethodType):
self.__dict__[name] = rebind(value, self)
elif isinstance(value, types.MethodType):
self.__dict__[name] = rebind(value, self)
else:
self.__dict__[name] = value

def __getattr__(self, name):
if name in self.__dict__.keys():
# seems superfluous; if the attribute exists, __getattr__
# isn't called
return self.__dict__[name]
else:
# scan "ancestors" for this name...
# left-right based on name, depth first
items = self.__dict__.items()
items.sort()
for attrname, obj in items:
if attrname.endswith("_p"):
try:
z = obj.__getattr__(name)
except AttributeError:
pass
else:
if isinstance(z, types.MethodType):
z = rebind(z, self)
return z
raise AttributeError, name

Object = SelfObject()

Jul 18 '05 #5
Stephan Diehl <st*****************@gmx.net> wrote in message news:<bt*************@news.t-online.com>...
Tobias Windeln wrote:

I'm looking for suggestions on object-based inheritance
in Python. Automatic forwarding (often called delegation)
in Python is easy:


Have a look at Hans Nowaks 'selfish' implementation:
http://zephyrfalcon.org/download/selfish-0.4.2.zip

This is a pythonesque interpretation of the 'self' language by Sun.
By the way, if you are googling, you want probably look for 'prototype based
languages'.


Seems like prototype-based languages are catching up the attention of
people. I have looked at them recently. My feeling is that somehow
main development stopped around 1997. I have looked at Io (I know it's
born in 2002, but the ideas come from before), but I just get the
feeling that Io is not "clean" enough. Anyway, I think that instead of
designing final languages, it's a better idea to make *prototype*
languages (sorry for the pun) and experiment with various features.
One problem I've seen in Io is that they started to write software,
when the language itself is not well-defined yet. And so, you make
changes to the language, and you have to make corrections to large
body of existing code. And, also, once too much code is written with
existing language, it becomes really hard to make language changes
later: too much work to update legacy packages.

There are a few problems with current programming languages that only
come to bite you at large scale projects (Multiple Inheritance,
Metaprogramming, AOP, Multiple Version handling,
Transactional/Incremental programming with real-time rollback/undo,
ideas from Functional languages, etc.) And my experience has been that
the more complex your project becomes, the more you wish you had a
simple, clean, solid, powerful theoretical foundation for your
programming language. Prototype-based seems the right direction to go,
but I am kind of disappointed at all existing prototype-based
languages out there. Somehow something happened in 1997 that stopped
research in this direction. And now the prototype-based languages seem
so much behind. It's like time has been frozen for 6 years.

regards,

Hung Jung
Jul 18 '05 #6

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

Similar topics

28
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()',...
9
by: Keith Rowe | last post by:
Hello, I am trying to reference a Shockwave Flash Object on a vb code behind page in an ASP.NET project and I receive the following error: Guid should contain 32 digits with 4 dashes...
11
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me understand the different ways to do the same thing in...
44
by: Steven T. Hatton | last post by:
This may seem like such a simple question, I should be embarrassed to ask it. The FAQ says an object is "A region of storage with associated semantics." OK, what exactly is meant by "associated...
9
by: Andrew Au | last post by:
Dear all, I am trying to write a piece of software that use Object Oriented design and implement it with C, I did the following == In Object.h == typedef struct ObjectStructure* Object; ...
5
by: Matthew | last post by:
I have a nice little Sub that saves data in a class "mySettings" to an XML file. I call it like so: Dim mySettings As mySettings = New mySettings mySettings.value1 = "someText" mySettings.value2...
4
by: Luke Matuszewski | last post by:
Here are some questions that i am interested about and wanted to here an explanation/discussion: 1. (general) Is the objectness in JavaScript was supported from the very first version of it (in...
5
by: Michael Moreno | last post by:
Hello, In a class I have this code: public object Obj; If Obj is a COM object I would like to call in the Dispose() method the following code: ...
26
by: yb | last post by:
Hi, Is there a standard for the global 'window' object in browsers? For example, it supports methods such as setInterval and clearInterval, and several others. I know that w3c standardized...
3
by: User1014 | last post by:
A global variable is really just a property of the "Global Object", so what does that make a function defined in the global context? A method of the Global Object? ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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:
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...

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.