Takes exactly 3 arguments (4 given)

▼魔方 西西 提交于 2020-01-28 09:59:35

问题


i'm refactoring code in order to add object orientation and am just testing the code.

pattern = r"((([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])[ (\[]?(\.|dot)[ )\]]?){3}([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))"

class Lineobject(object):

        def __init__(self, pattern, line):
            self.ip = self.getip(self, pattern, line)

        def getip (self, pattern, line):
                for match in re.findall(pattern, line):
                    results = ''
                    ips = match[0]
                    usergeneratedblacklist.write(ips)
                    usergeneratedblacklist.write('\n')
                    return ips

When instantiating the class below I am getting an odd error. That of getip() takes exactly 3 arguments (4 given) which i do not know how to resolve.

for theline in f:

    if "Failed password" in theline:

        lineclass = Lineobject(pattern, theline)

    else:
        pass

回答1:


You are giving self.getip() four arguments because Python automatically adds in first self argument for bound methods. The expression:

self.getip(self, pattern, line)

results in:

getip(self, self, pattern, line)

which is four arguments.

Don't pass in self again:

self.ip = self.getip(pattern, line)

The very act of looking up the method on the instance (via self.getip) binds the method to handle that first argument for you.




回答2:


When calling an instance method, you don't pass the instance explicitly

ie.

self.ip = self.getip(pattern, line)


来源:https://stackoverflow.com/questions/29576993/takes-exactly-3-arguments-4-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!