I have a file that contains a class, its called test.py. How can i call on that class within another file called xml.py?

Recommended Answers

All 4 Replies

Just make sure they are both in the same directory (probably c:/python or something like that).
Then you can just import the other file and use it like it is a module.

import test.py  #just imports the file

from test.py import * #brings every class and function from the file in the current scope

ok i got that working but now how do i call the class a function

here is the class file

#!/usr/bin/python
import urllib2
class sendmessage:
    def send_SMS(message):
        user = 'username'
        passwrd = 'password'
        destination = 'number'
        origin = 'Adam'
        mess = message
        callback = 'http://adamplowman.com/form/callback.php?reportcode=%code&destinationnumber=%dest&myreference=123'
        path = '/sms/postmsg.php'
        smsurl = path+'?username='+user+'&password='+passwrd+'&to_num='+destination+'&message='+mess+'&originator='+origin
        array_server = ['gw1.aql.com','gw11.aql.com','gw2.aql.com','gw22.aql.com']

        for server in array_server:
            print "http://"+server+smsurl
            response = urllib2.urlopen("http://"+server+smsurl)
            if response:
                sent = response.read()
                return sent

this is how i am opting to call it

from test import sendmessage 
x = sendmessage()
print x.send_SMS("error")

and i get the error

Traceback (most recent call last):
File "/Users/adamplowman/Documents/Uni/project/python/a.py", line 3, in <module>
print x.send_SMS('error')
TypeError: send_SMS() takes exactly 1 argument (2 given)
>>>

Because as you defined it, send_SMS is a method of the class sendmessage. So when you call x.send_SMS('error') , 2 arguments are passed, the first is x , the other is 'error' . There are 2 solutions, either you add an argument: def send_SMS(self, message): , or, if you don't need the instance, you define it as a static method like this

class ...:
    @staticmethod
    def send_SMS(message):
        ...
let us say you have a python file(new.py) in folder named POST

from POST.new import *

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.