0

Is it possible to call methods on a default object? To explain what I mean, here's an example:

There's Foo.py with a class:

class Foo:
    def fooMethod():
        print "doSomething"

fooObject = Foo()

And another pythonscript Bar.py:

from Foo import *
// what I can do now is:
fooObject.fooMethod()
// what I need is that this:
fooMethod()
// is automatically executed on fooObject if the method was not found in Bar.py

Is there any possibility to make this work? What I need is to set a "default"-object on which methods are executed if the method was not found.

1 Answer 1

3

This has been done in Python's random module. They use a simple and straight-forward solution:

class Foo:
    def foo_method(self):
        print "do something"

foo_object = Foo()
foo_method = foo_object.foo_method

It would also be possible to write some introspection code to automatically propagate all methods of Foo to the module namespace, but I recommend against doing so.

Sign up to request clarification or add additional context in comments.

4 Comments

I know this is possible. The problem I have is that foo_object can be changed to be different object with different methods in the one module, so I would have to write:
Sorry ignore first comment please ^^.. The problem I have is that foo_object can be changed to be a different object with different methods in the module I'm importing, so I would have to write an alias for every possible object-method that foo_object can have. I would'nt want to do that.
@kel: If foo_object changes, you want the module contents to magically change as well? This sounds like a terrible idea. Morover, what about other modules that did from Foo import * before? They will have to reimport everything. (Using from Foo import * in production code is generally a bad idea.)
What I was really looking for was the functionality of getattr for classes or the setattr(module,name,attribute). I'm sorry, I think my question was not so clear. Thank you for your answer anyway =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.