Python类错误TypeError:__ init __()缺少1个必需的位置参数:'self'

问题描述 投票:-3回答:3

我有一个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 =无,I =无是路径。

我试着在我的班级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类有理论上的理解。但是,从未尝试过。所以任何帮助都会很棒!

python class os.walk
3个回答
3
投票

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


1
投票

__init__(构造函数)不能是静态方法。当你调用类MyClass()的构造函数时,会调用__init__方法。 self是该方法所属对象的占位符参数 - 它允许您访问该对象的属性。但如果你把它变成@staticmethod那么self被解释为正常的论点 - 这就是你看到Required 1 argument错误的原因。


1
投票

在定义@staticmethod之前删除__init__装饰器。当您使用@staticmethod修饰方法时,此方法不会将对象作为隐式的第一个参数(因此您不应将self放在其签名中)。

例如,在下面,您可以看到在不传递任何显式参数的情况下调用这两个方法,即使A.non_static需要参数self。这是因为通常的方法隐式接收self,而静态方法则没有。

>>> class A:
...     @staticmethod
...     def static():  # No `self` argument
...         print('static')
...     def non_static(self):  # Here `self` is required
...         print('non-static')

>>> a = A()  # a is an instance of A
>>> a.static()
'static'
>>> a.non_static()
'non-static'
© www.soinside.com 2019 - 2024. All rights reserved.