【问题标题】:My function works on its own but not callable from class我的函数独立工作,但不能从类中调用
【发布时间】:2022-01-13 08:30:34
【问题描述】:

我做了一个如下的类:

class Plugins:

    def __init__(self):
        pass

    
    def voter_rep(self, loc, start_header, end_header):
        
        self.loc = loc
        ocr_xml = AbbyyXML(loc)
        xml_doc = XMLDoc(ocr_xml, CONSTANTS)
        xml_doc.split_words("", False)

        self.start_header = start_header
        self.end_header = end_header

        header_pages = xml_doc.se_page(start_header, end_header)
        ## and stuff
        voter_dict = {'Voter':[], 'Record_Key':[], 'Comments':[]}
        ## and stuff
        return voter_dict, rep_dict

如果我在类之外单独运行方法函数,它完全可以正常工作,即如果我将函数编写为:

def voter_rep(loc, start_header, end_header):
            
            
            ocr_xml = AbbyyXML(loc)
            xml_doc = XMLDoc(ocr_xml, CONSTANTS)
            xml_doc.split_words("", False)
    
            header_pages = xml_doc.se_page(start_header, end_header)
            ## and stuff
            voter_dict = {'Voter':[], 'Record_Key':[], 'Comments':[]}
            ## and stuff
     return voter_dict, rep_dict

仅在函数中,我摆脱了self,只有voter_rep(loc, start_header, end_header),但是当我想从类中调用它时,我执行plugins.voter_rep(loc, start_header, end_header),它不起作用,它返回:

NameError: name 'plugins' is not defined

我想知道为什么我的函数可以自己工作但不能从类中调用?

【问题讨论】:

    标签: python function class oop


    【解决方案1】:
    Plugins.voter_rep(loc, start_header, end_header)
    

    注意大写字母。

    【讨论】:

    • 但在这种情况下,问题是:为什么这个函数甚至是一个类的方法?
    • 我的愚蠢错误:P
    • @Matthias 因为它是更大模块的一部分...
    【解决方案2】:

    你可以的

    plugins = Plugins()
    loc = #some val
    start_header = #some val
    end_header = #some val
    plugins.voter_rep(loc, start_header, end_header)
    

    如错误消息所示,您使用的是小写的“p”而不是大写字母。另外由于它不是静态函数,所以不能通过类名来调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      相关资源
      最近更新 更多