473,666 Members | 2,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to dispatch objects depending on their class


Hi all.

I have a couple of question regarding the following situation:

class A(object):
def __init__(self):
pass

class B(object):
def __init__(self):
A.__init__(self )

def func(object):
if isinstance(obje ct, A):
do_something_wi th_A(object)
elif isinstance(obje ct, B):
do_something_wi th_B(object)

Note that in my real problem I cannot move the logic of func to the
class A and B because I will have a hierarchy also for func. Then I need
a way to dispatch the object to the right function. I thought about
using a dictionary, like:

FUNC = {"<class '__main__.A'>": do_something_wi th_A,
"<class '__main__.B'>": do_something_wi th_B}

def func(object):
FUNC[type(object)](object)

But: (1) I am not sure of what the type(object) function return. In this
case A and B are in the __main__ namespace (assuming this is how is
called), but if they are in a module; (2) I am not sure if it is
efficient; and finally (3): probably there is a better way to do it
(this is always a safe assumption).

I hope my problem is clear, and excuse me if I am asking about something
that is common knowledge, but I don't even know what to google for...

thanks, curzio
Jul 18 '05 #1
14 1464
Curzio Basso wrote:
FUNC = {"<class '__main__.A'>": do_something_wi th_A,
"<class '__main__.B'>": do_something_wi th_B}

def func(object):
FUNC[type(object)](object)
You'll have to modify that slightly for it to work. It will be very
efficient, too.

func_dict = {A: do_something_wi th_A,
B: do_something_wi th_B}
def func(obj):
func_dict[obj.__class__](obj)

Using classes as keys avoids the ambiguity you fear. The overhead will be
one dictionary lookup and a function call. The main drawback of this simple
approach is that it does not search the inheritance tree but insists on an
exact class match.
I hope my problem is clear, and excuse me if I am asking about something
that is common knowledge, but I don't even know what to google for...


Maybe

python generic dispatch

Peter
Jul 18 '05 #2
It should not be a problem to use the actual class object as keys in the
dict and the functions as values. No need to convert the class to
strings.

So why can't they be static methods of the classes exactly? That would
be simpler, however the dict will work efficiently.

-Casey

On Tue, 10 Aug 2004 16:35:48 +0200
Curzio Basso <cu**********@u nibas.ch> wrote:

Hi all.

I have a couple of question regarding the following situation:

class A(object):
def __init__(self):
pass

class B(object):
def __init__(self):
A.__init__(self )

def func(object):
if isinstance(obje ct, A):
do_something_wi th_A(object)
elif isinstance(obje ct, B):
do_something_wi th_B(object)

Note that in my real problem I cannot move the logic of func to the
class A and B because I will have a hierarchy also for func. Then I
need a way to dispatch the object to the right function. I thought
about using a dictionary, like:

FUNC = {"<class '__main__.A'>": do_something_wi th_A,
"<class '__main__.B'>": do_something_wi th_B}

def func(object):
FUNC[type(object)](object)

But: (1) I am not sure of what the type(object) function return. In
this case A and B are in the __main__ namespace (assuming this is how
is called), but if they are in a module; (2) I am not sure if it is
efficient; and finally (3): probably there is a better way to do it
(this is always a safe assumption).

I hope my problem is clear, and excuse me if I am asking about
something that is common knowledge, but I don't even know what to
google for...

thanks, curzio
--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #3
Curzio Basso wrote:

Hi all.

I have a couple of question regarding the following situation:

class A(object):
def __init__(self):
pass

class B(object):
def __init__(self):
A.__init__(self )

def func(object):
if isinstance(obje ct, A):
do_something_wi th_A(object)
elif isinstance(obje ct, B):
do_something_wi th_B(object)

Note that in my real problem I cannot move the logic of func to the
class A and B because I will have a hierarchy also for func. Then I need
a way to dispatch the object to the right function.


I saw something like a multi-methods implementation in Python somewhere,
this may interest you.
http://www-106.ibm.com/developerwork.../l-pydisp.html

Jul 18 '05 #4
Visitor Pattern?
Jul 18 '05 #5
Curzio Basso <cu**********@u nibas.ch> wrote in message news:<41******* *@maser.urz.uni bas.ch>...
Hi all.

I have a couple of question regarding the following situation:

class A(object):
def __init__(self):
pass

class B(object):
def __init__(self):
A.__init__(self )

def func(object):
if isinstance(obje ct, A):
do_something_wi th_A(object)
elif isinstance(obje ct, B):
do_something_wi th_B(object)

Note that in my real problem I cannot move the logic of func to the
class A and B because I will have a hierarchy also for func. Then I need
a way to dispatch the object to the right function. I thought about
using a dictionary, like:

FUNC = {"<class '__main__.A'>": do_something_wi th_A,
"<class '__main__.B'>": do_something_wi th_B}

def func(object):
FUNC[type(object)](object)

But: (1) I am not sure of what the type(object) function return. In this
case A and B are in the __main__ namespace (assuming this is how is
called), but if they are in a module; (2) I am not sure if it is
efficient; and finally (3): probably there is a better way to do it
(this is always a safe assumption).

I hope my problem is clear, and excuse me if I am asking about something
that is common knowledge, but I don't even know what to google for...

thanks, curzio

At my opinion you try to do something outside a class which should
be a basic task of OOP. Why not let the instances do their class-specific
things:

class A(object):
def __init__(self):
pass
def do_something(se lf):
""" Do A-specific things """
pass

class B(object):
def __init__(self):
A.__init__(self )
def do_something(se lf):
""" Do B-specific things """
pass

a=A()
b=B()
a.do_something( )
b.do_something( )

Regards
Peter
Jul 18 '05 #6
Peter Abel wrote:
At my opinion you try to do something outside a class which should
be a basic task of OOP. Why not let the instances do their class-specific
things:


I know that this situation would be typically handled by putting the
logic in the class hierarchy, but as I wrote I don't want this. In fact,
as cm******@hotmai l.com pointed out, at the end what I want to implement
is a visitor pattern (maybe I should have simply mentioned this). In C++
then the right implementations are chosen at compile time because of the
function overloading, but in Python I have to find a different way to
implement this.

cheers, curzio
Jul 18 '05 #7
Curzio Basso wrote:
class B(object):
def __init__(self):
A.__init__(self )


typo. this should be:

class B(A):
def __init__(self):
A.__init__(self )
Jul 18 '05 #8
cm******@hotmai l.com wrote:
Visitor Pattern?


Actually, I thought what I was describing was a visitor pattern but I am
probably wrong.

Is it correct that in the visitor pattern the dispatching would be
delegated to the classes, like with:

class A(object):
def __init__(self):
pass
def accept(self, visitor)
visitor.do_some thing_with_A(se lf)

class B(A):
def __init__(self):
A.__init__(self )
def accept(self, visitor)
visitor.do_some thing_with_B(se lf)

class Visitor(object) :
def __init__(self):
pass
def do_something_wi th_A(self, object):
pass
def do_something_wi th_B(self, object):
pass

Then I would call

a = A()
b = B()
v = Visitor()
a.accept(v)
b.accept(v)

Is this correct?

thanks, curzio
Jul 18 '05 #9
Bruno Desthuilliers wrote:
I saw something like a multi-methods implementation in Python somewhere,
this may interest you.
http://www-106.ibm.com/developerwork.../l-pydisp.html


looks interesting. thanks for the link, I'll post some comment if I find
it useful for my problem.

cheers, curzio
Jul 18 '05 #10

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

Similar topics

6
2289
by: Garma | last post by:
According to what I have learnt so far, instantiating global objects should be the last resort. Is there any reasons why so? Sometimes some objects or their pointers have to be shared among several other objects, I'd like to know how this is handled commonly. Could someone elaborate on this? Another situation is some objects could be shared among several threads. How to handle it commonly?
4
2396
by: Leslaw Bieniasz | last post by:
Cracow, 20.09.2004 Hello, I need to implement a library containing a hierarchy of classes together with some binary operations on objects. To fix attention, let me assume that it is a hierarchy of algebraic matrices with the addition operation. Thus, I want to have a virtual base class class Matr;
1
2317
by: Thomas Matthews | last post by:
Hi, I'm looking for an efficient method to deep copy containers of fields. A Field is a parent class with children such as Integer_Field, String_Field, and Date_Field, etc. The algorithm / method should ensure that an Integer_Field is not copied (assigned) to a String_Field or other descendant of Field. I have looked at the Visitor design pattern with
3
5042
by: Dan Vogel | last post by:
I'd like to find an elegant solution to the problem of calling a certain function based on the types of two parameters. In my case, the functions compute the distance between different types of geometric objects, and I want to call the function that gives me the most accurate distance. I have a base class called Shape with basic functionality: Shape
3
6933
by: tyler.schlosser | last post by:
Hi there, I am trying to launch a program called AmiBroker using the command: AB = win32com.client.Dispatch("Broker.Application") However, I have a dual-core CPU and would like to launch two instances of AmiBroker. I know it is possible to run two instances simultaneously since it is easy to do manually by double-clicking the AmiBroker.exe file twice. However, when I write two lines of code like this:
27
2551
by: SasQ | last post by:
Hello. I wonder if literal constants are objects, or they're only "naked" values not contained in any object? I have read that literal constants may not to be allocated by the compiler. If the Standard is saying that "object is a region of storage", I deduce from that that literal constants aren't objects because they may not be alocated as regions of storage in the memory.
3
3770
by: Tigera | last post by:
Greetings, I too have succumbed to the perhaps foolish urge to write a video game, and I have been struggling with the implementation of multiple dispatch. I read through "More Effective C++" by Scott Meyers, and though I am impressed with his implementation, I wanted to find a way to use multiple dispatch in a way that was less complicated. Forgive me if the result, below, has been posted before or written of before - I haven't read...
14
6008
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared static inside functions (i.e. local static objects) 5. objects declared at file scope.
19
10744
by: Daniel Pitts | last post by:
I have std::vector<Base *bases; I'd like to do something like: std::for_each(bases.begin(), bases.end(), operator delete); Is it possible without writing an adapter? Is there a better way? Is there an existing adapter? Thanks, Daniel.
0
8440
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
8780
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8636
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7378
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4192
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
4358
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2765
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
2005
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1763
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.