By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,660 Members | 1,102 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,660 IT Pros & Developers. It's quick & easy.

Passing the module as an argument

P: 144

I have question, I'm trying to pass the module itself when calling a function in another module. Let me illustrate:
import test2

def hello():
print "hello there"
def call(object):

Traceback (most recent call last):
File "", line 6, in <module>
NameError: name 'self' is not defined

when I google, I see that self is mostly refered to classes. Is this only for classes or did I miss a link?

Thx in advance
Mar 13 '08 #1
Share this Question
Share on Google+
4 Replies

P: 314
Yes, self refers to an instance of a class typically, but really you can make the keyword be anything (self is just kinda the standard). You are doing something strange in your code and I can't quite understand what it is that you're trying.

You will want to make a class with the function hello() being of that class, then do something like the following:
Expand|Select|Wrap|Line Numbers
  1. >>> class mycls:
  2. ...     def hello(self):
  3. ...         print "Hello world"
  4. ...     
  5. >>> my_class = mycls()
  6. >>> def call(obj):
  7. ...     obj.hello()
  8. ...     
  9. >>> call(my_class)
  10. Hello world
  11. >>> 
Mar 13 '08 #2

P: 144
That works, but without using classes it isn't possible?
I could do it like that, but then I would have to rewrite a large portion of code :)
Mar 13 '08 #3

P: 314
You have to understand that using a '.' and function ( ie, object.hello() ) means that hello() is an attribute of object. The only way that something is an attribute is either through a module or a class.

You could do it through another script, so that hello is an attribute as in:
Expand|Select|Wrap|Line Numbers
  1. import test
  2. test.hello()
Mar 13 '08 #4

P: 144
The thing is, I'm writing a plug in system for a program and the plug in has to be able to get some information from the programming calling the plug in in the first place. I thought I was able to fix this quickly by providing the module as a argument.

But I guess I'll make a small class like below (probably not the fastest, but it will limit time coding)
Expand|Select|Wrap|Line Numbers
  1. import test2
  3. def hellof():
  4.     print "hello from the function"
  6. class Test:
  7.     def __init__(self):
  8.         print "loaded"
  9.     def hello(self):
  10.         hellof()
  12. obj = Test()
Expand|Select|Wrap|Line Numbers
  1. def call(object):
  2.     object.hello()

Thank you very much for this fast response.
Mar 13 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.