Defining class methods outside of classes

Discussion in 'Python' started by Lord Landon, May 3, 2006.

  1. Lord Landon

    Lord Landon Guest

    Hi, I'm working on a bot written in python. It will consist of a
    mostly empty class that will then call a loader which in turn defines
    functions and adds them to the class. At the moment, I do this by
    using execfile(file,globals()) and calling a load(bot) method defined
    in every "module" which takes the functions defined in that perticular
    module and does bot.function=function. The problem with that is when I
    call bot.function() self doesn't get passed as an argument to the
    function. Is there anything I can do to sort this besides calling
    bot.function(bot, ...) everytime?

    --
    Lord Landon rules over all!
     
    Lord Landon, May 3, 2006
    #1
    1. Advertising

  2. Lord Landon

    Peter Otten Guest

    Lord Landon wrote:

    > Hi, I'm working on a bot written in python. It will consist of a
    > mostly empty class that will then call a loader which in turn defines
    > functions and adds them to the class. At the moment, I do this by
    > using execfile(file,globals()) and calling a load(bot) method defined
    > in every "module" which takes the functions defined in that perticular
    > module and does bot.function=function. The problem with that is when I
    > call bot.function() self doesn't get passed as an argument to the
    > function. Is there anything I can do to sort this besides calling
    > bot.function(bot, ...) everytime?


    Either add the method to the class or make it an instance method.

    >>> class Bot(object):

    .... def __init__(self):
    .... self.name = "bot"
    ....
    >>> bot = Bot()
    >>> def method(self): print "hello from", self.name

    ....
    >>> Bot.greet = method
    >>> bot.greet()

    hello from bot
    >>> import new
    >>> bot.hello = new.instancemethod(method, bot)
    >>> bot.hello()

    hello from bot

    Peter
     
    Peter Otten, May 4, 2006
    #2
    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. Jasper Pearlman

    Defining methods outside of script tags

    Jasper Pearlman, Aug 16, 2004, in forum: ASP .Net
    Replies:
    3
    Views:
    359
  2. Chris  Portka
    Replies:
    3
    Views:
    319
    David Harmon
    Dec 6, 2006
  3. chhenning
    Replies:
    5
    Views:
    382
    chhenning
    Feb 13, 2008
  4. Kenneth McDonald
    Replies:
    5
    Views:
    373
    Kenneth McDonald
    Sep 26, 2008
  5. Cliff  Williams

    defining classes-- different methods

    Cliff Williams, Nov 26, 2006, in forum: Javascript
    Replies:
    25
    Views:
    309
    Bart Van der Donck
    Nov 29, 2006
Loading...

Share This Page