Extending objects by a method?

Discussion in 'Python' started by Karsten Wutzke, Jul 15, 2010.

  1. Hello,

    I'm new to Python so beware.

    I have a hierarchical object structure which I iterate over (the
    elements/classes of interest). I would like to apply the Visitor
    pattern onto this object structure, so I must add an "accept" method
    to every object (I'm interesting in) for the Visitor pattern to work.

    Is there any Python-inbuilt way to dynamically add a method or do I
    have to wrap each iterated object into a Decorator supplying the
    accept method? The latter would mean having to rebuild the (part)
    hierarchy with the Decorator objects before running the Visitor, which
    I'd like to avoid.

    Karsten
    Karsten Wutzke, Jul 15, 2010
    #1
    1. Advertising

  2. Small correction: I probably have to add a method to a class, so that
    every object instantiated not by me has the desired functionality.

    Karsten
    Karsten Wutzke, Jul 15, 2010
    #2
    1. Advertising

  3. Karsten Wutzke

    Tim Chase Guest

    On 07/15/2010 06:45 AM, Karsten Wutzke wrote:
    > Small correction: I probably have to add a method to a class, so that
    > every object instantiated not by me has the desired functionality.


    You mean like:

    >>> class Foo:

    .... def __init__(self, greeting):
    .... self.greeting = greeting
    ....
    >>> f = Foo("Hello")
    >>> def greet(self, other):

    .... print "%s, %s" % (self.greeting, other)
    ....
    >>> Foo.greet = greet
    >>> f.greet("world")

    Hello, world


    -tkc
    Tim Chase, Jul 15, 2010
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Johannes Zellner
    Replies:
    3
    Views:
    451
    Fredrik Lundh
    Jan 18, 2006
  2. Jon Clements

    Extending built-in objects/classes

    Jon Clements, Jul 3, 2006, in forum: Python
    Replies:
    5
    Views:
    340
    John Machin
    Jul 3, 2006
  3. 7stud
    Replies:
    11
    Views:
    668
    Dennis Lee Bieber
    Mar 20, 2007
  4. jdetaeye
    Replies:
    0
    Views:
    497
    jdetaeye
    Mar 18, 2008
  5. Asfand Yar Qazi
    Replies:
    0
    Views:
    117
    Asfand Yar Qazi
    Dec 1, 2003
Loading...

Share This Page