从其他类运行python方法时出现异常

Exception when running a Python method from another class

这是我的密码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import urllib2
import urllib
import json
from BeautifulSoup import BeautifulSoup

class parser:
   """
    This class uses the Beautiful Soup library to scrape the information from
    the HTML source code from Google Translate.

    It also offers a way to consume the AJAX result of the translation, however
    encoding on Windows won't work well right now so it's recommended to use
    the scraping method.
   """


    def fromHtml(self, text, languageFrom, languageTo):
       """
        Returns translated text that is scraped from Google Translate's HTML
        source code.
       """

        langCode={
           "arabic":"ar","bulgarian":"bg","chinese":"zh-CN",
           "croatian":"hr","czech":"cs","danish":"da","dutch":"nl",
           "english":"en","finnish":"fi","french":"fr","german":"de",
           "greek":"el","hindi":"hi","italian":"it","japanese":"ja",
           "korean":"ko","norwegian":"no","polish":"pl","portugese":"pt",
           "romanian":"ro","russian":"ru","spanish":"es","swedish":"sv" }

        urllib.FancyURLopener.version ="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008070400 SUSE/3.0.1-0.1 Firefox/3.0.1"

        try:
            postParameters = urllib.urlencode({"langpair":"%s|%s" %(langCode[languageFrom.lower()],langCode[languageTo.lower()]),"text":text,"ie":"UTF8","oe":"UTF8"})
        except KeyError, error:
            print"Currently we do not support %s" %(error.args[0])
            return

        page = urllib.urlopen("http://translate.google.com/translate_t", postParameters)
        content = page.read()
        page.close()

        htmlSource = BeautifulSoup(content)
        translation = htmlSource.find('span', title=text )
        return translation.renderContents()


    def fromAjaxService(self, text, languageFrom, languageTo):
       """
        Returns a simple string translating the text from"languageFrom" to
       "LanguageTo" using Google Translate AJAX Service.
       """

        LANG={
           "arabic":"ar","bulgarian":"bg","chinese":"zh-CN",
           "croatian":"hr","czech":"cs","danish":"da","dutch":"nl",
           "english":"en","finnish":"fi","french":"fr","german":"de",
           "greek":"el","hindi":"hi","italian":"it","japanese":"ja",
           "korean":"ko","norwegian":"no","polish":"pl","portugese":"pt",
           "romanian":"ro","russian":"ru","spanish":"es","swedish":"sv" }

        base_url='http://ajax.googleapis.com/ajax/services/language/translate?'
        langpair='%s|%s'%(LANG.get(languageFrom.lower(),languageFrom),
                          LANG.get(languageTo.lower(),languageTo))
        params=urllib.urlencode( (('v',1.0),
                           ('q',text.encode('utf-8')),
                           ('langpair',langpair),) )
        url=base_url+params
        content=urllib2.urlopen(url).read()
        try: trans_dict=json.loads(content)
        except AttributeError:
            try: trans_dict=json.load(content)
            except AttributeError: trans_dict=json.read(content)
        return trans_dict['responseData']['translatedText']

现在在另一个名为testinggrounds.py的类中,我想尝试这两种方法,但得到了以下错误:

1
2
3
from Parser import parser

print parser.fromHtml("Hello my lady!","English","Italian")

回溯(最近的最后一次调用):文件"c:userssergio.tapiadocumentsetbeansprojectsabylonpythonsrc estinggrounds.py",第3行,inprint parser.fromhtml("你好,我的女士!""English"、"Italian")类型错误:必须使用Parser实例作为第一个参数调用未绑定的方法fromHTML()(改为获取str实例)


您必须有一个parser类的实例,而不是对类本身调用方法。

1
2
3
from Parser import parser

print parser().fromHTML("Hello my lady!","English","Italian")

1
2
3
4
from Parser import parser

p = parser()
p.fromHTML(...)

或者,您可以使fromHTML成为静态方法:

1
2
3
4
5
class parser(object):   # you should probably use new-style classes
    ...
    @staticmethod
    def fromHTML(...):
        ...

然后你可以像这样使用:

1
2
3
from Parser import parser

print parser.fromHTML(...)


如果您想将fromhtml()用作静态方法,如果您实际上不需要访问解析器中的任何数据成员,则非常有用,您需要这样做(为了简洁起见而剪切)

1
2
3
4
class parser:
    @staticmethod
    def fromHtml(text, languageFrom, languageTo):
         # etc.

或者,如果您希望它同时是一个静态方法,并且能够成为一个实例方法…

1
2
3
4
class parser:
    @classmethod
    def fromHtml(self, text, languageFrom, languageTo):
         # etc.

现在可以将其用作parser.fromHtml()parser().fromHtml()

看看您的代码,我应该认为您只需要一个静态方法。