Python 类错误 TypeError: __init__() 缺少 1 个必需的位置参数:

我有一个 python 类,如下所示。


class copyingfiles():

    @staticmethod

    def __init__(self, x=[], y=[], z=None, i=None):


        self.x = x

        self.y = y

        self. z = z

        self.i= i

    @staticmethod

    def mover(self):

        x = self.x

        y= self.y

        z = self.z

        i= self.i

        for sam in x.keys():

            for pids in y:

                PID = pids.split('_')[1]

                if sam in pids:

                    destination = z + "/rep/" + "study/" +  id  + "/" + sam + "/rh/"+ "fg/"

                    if not os.path.isdir(destination):

                        pathlib.Path(destination).mkdir(parents=True, exist_ok=True)

                    for files in fnmatch.filter(os.listdir(i), pat="*.gz"):

                        if sam in files:

                            shutil.copy(os.path.join(i,files), os.path.join(destination,files))


                return(destination)

其中 x=[], y=[] 是字典,z=None, I=None 是路径。


我尝试在我的班级中调用该函数copyingfiles,如下所示,


testInstance = copyingfiles()

testInstance.mover(x, y,z,i)

它抛出以下错误,


TypeError                                 Traceback (most recent call last)

<ipython-input-50-7da378685d71> in <module>

----> 1 testInstance = copyingfiles()

      2 testInstance.mover(x, y,z,i)


TypeError: __init__() missing 1 required positional argument: 'self'

我对python类有理论上的理解。然而,从未尝试过。所以任何帮助都会很棒!


噜噜哒
浏览 1459回答 3
3回答

慕容708150

只需删除@staticmethod,当您不想将方法链接到对象的实例时使用那些(即copyingfile.mover()。您还应该使用 PascalCase(首字母大写)重命名您的类并删除class copyingfiles.

莫回无

__init__(构造函数)不能是静态方法。当你调用类的构造函数MyClass()的__init__方法被调用。该self是到该方法属于对象的占位符参数-它可以让你访问该对象的属性。但是,如果您将其设为a,@staticmethod则将self其解释为正常参数 - 这就是您看到该Required 1 argument错误的原因。

慕田峪4524236

删除@staticmethod定义之前的装饰器__init__。当你用 装饰一个方法时@staticmethod,这个方法不会将对象作为隐式的第一个参数(所以你不应该self输入它的签名)。例如,在下面,您可以看到调用这两个方法时没有传递任何显式参数,即使A.non_static需要参数self。这是因为通常的方法会self隐式接收,而静态方法则不会。>>> class A:...&nbsp; &nbsp; &nbsp;@staticmethod...&nbsp; &nbsp; &nbsp;def static():&nbsp; # No `self` argument...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print('static')...&nbsp; &nbsp; &nbsp;def non_static(self):&nbsp; # Here `self` is required...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print('non-static')>>> a = A()&nbsp; # a is an instance of A>>> a.static()'static'>>> a.non_static()'non-static'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python