在顶部导入json模块时如何在类的方法中调用json.load

如果我从json导入load方法,则在调用load方法时,我无法理解json.load为什么会向我检索“ TypeError:load()接受1个位置参数,但给出了2个”。而是将其导入方法内部并调用game_data = load(file)函数。为什么?像其他所有方法一样,如何在顶部导入负载呢?

class start:
    from module_x import method_y
    from json import load

    def __init__(self,game,data = {}):
        self.name = game + '.json'
        self.data = data

def xyz():
        self.method_y() #calling other methods with self.method is okay

def loading(self,file = None): 
        if not file:
            file = self.name
        with open(file,'r') as file:
            game_data = self.load(file) #here is not okay
        return game_data

没关系:

 def loading(self,file = None): 
        from json import load
        if not file:
            file = self.name
        with open(file,'r') as file:
            game_data = load(file) 
        return game_data
mmtsky 回答:在顶部导入json模块时如何在类的方法中调用json.load

如果您应用适当的缩进,则问题在于您的实例将传递给所调用的方法。当您编写self.method()时,Python会调用method(self)

您可以导入模块json而不是方法,那么您将拥有self.module.method()

class start:
    import json

    def __init__(self,game,data = {}):
        self.name = game + '.json'
        self.data = data

    def loading(self,file = None): 
            if not file:
                file = self.name
            with open(file,'r') as file:
                game_data = self.json.load(file)
            return game_data

作为旁注:您应该避免将导入放置在文件开头以外的任何位置。来自PEP8的Python样式指南:

  

导入总是放在文件的顶部,紧随任何模块之后   注释和文档字符串,以及模块全局变量和常量之前。

,

问题是,模块“ json”的函数“ load”仅使用一个参数,但是由于它现在是您创建的类的方法,因此它将始终以“ self”作为第一个参数和传递的参数作为第二个。 因此,不可能将函数直接导入到类中。您只需要导入模块本身,或者将函数导入您的加载函数中,或者将最后一个选项导入文件顶部,只有您可以按预期的方式调用和使用它。

选项1:

class myClass:
    import json
    def myLoadindFunction(self,fileObject):
        fileContent = self.json.load(fileObject)

选项2:

class myClass:
    def myLoadindFunction(self,fileObject):
        from json import load
        fileContent = load(fileObject)

选项3:

from json import load
class myClass:
    def myLoadindFunction(self,fileObject):
        fileContent = load(fileObject)
本文链接:https://www.f2er.com/3128769.html

大家都在问