Python类错误TypeError:\uyu init_uu()缺少1个必需的位置参数:“self”

2024-10-01 07:47:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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中调用函数,如下所示

^{pr2}$

它抛出以下错误

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类有理论上的理解。然而,从未尝试过。所以任何帮助都太好了!在


Tags: pathinselfnoneforifinitos
3条回答

删除@staticmethod的定义之前的@staticmethod修饰符。当你用@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'

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

只需删除@staticmethod,当您不想将方法链接到对象的实例(即copyingfile.mover())时会用到这些。 您还应该用pascalase(第一个字母大写)重命名类,并删除class copyingfiles后面的括号。在

相关问题 更多 >