为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

噜噜哒 2022-01-05 10:50:40
我有一个 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类有理论上的理解。然而,从未尝试过。所以任何帮助都会很棒!
查看完整描述

3 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

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

查看完整回答
反对 回复 2022-01-05
?
莫回无

TA贡献1865条经验 获得超7个赞

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


查看完整回答
反对 回复 2022-01-05
?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

删除@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'


查看完整回答
反对 回复 2022-01-05
  • 3 回答
  • 0 关注
  • 1458 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号