简体   繁体   中英

TypeError: __init__() takes 2 positional arguments but 3 were given Python 3?

I am unable to figure out what is causing this strange error. To me it looks like I am providing the right number of args but I have no idea why I am getting such an exception.

class FileParser(object):

    def __init__(self,file_name,category):
        self.file_name=file_name
        self.category=category



class SchoolParser(FileParser):

    def __init__(self,file_name,category):
        FileParser.__init__(self,file_name,category)

views.py

schoolparser = SchoolParser(file_name,category)

logs

 schoolparser = SchoolParser(file_name,category)
TypeError: __init__() takes 2 positional arguments but 3 were given

I did not get this error but a different error. That was because after the class is created, you need to instantiate it with an object which in your case will be the name of file and category.

>>>class FileParser(object):
       def __init__(self,file_name,category):
           self.file_name=file_name
           self.category=category

   class SchoolParser(FileParser):
       def __init__(self,file_name,category):
           FileParser.__init__(self,file_name,category)

>>>schoolparser = SchoolParser(file_name,category)

   NameError: name 'file_name' is not defined

This was because I was not instantiating the class with proper arguments. This got it done:

>>>schoolparser = SchoolParser('banana', 'fruit')

   <__main__.SchoolParser at 0x1bf159ed860>

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM