TypeError: method() takes 1 positional argument but 2 were given

前端 未结 9 1000
孤街浪徒
孤街浪徒 2020-11-22 05:02

If I have a class...

class MyClass:

    def method(arg):
        print(arg)

...which I use to create an object...

my_objec         


        
9条回答
  •  再見小時候
    2020-11-22 05:30

    It occurs when you don't specify the no of parameters the __init__() or any other method looking for.

    For example:

    class Dog:
        def __init__(self):
            print("IN INIT METHOD")
    
        def __unicode__(self,):
            print("IN UNICODE METHOD")
    
        def __str__(self):
            print("IN STR METHOD")
    
    obj=Dog("JIMMY",1,2,3,"WOOF")
    

    When you run the above programme, it gives you an error like that:

    TypeError: __init__() takes 1 positional argument but 6 were given

    How we can get rid of this thing?

    Just pass the parameters, what __init__() method looking for

    class Dog:
        def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
            self.name_of_dog = dogname
            self.date_of_birth = dob_d
            self.month_of_birth = dob_m
            self.year_of_birth = dob_y
            self.sound_it_make = dogSpeakText
    
        def __unicode__(self, ):
            print("IN UNICODE METHOD")
    
        def __str__(self):
            print("IN STR METHOD")
    
    
    obj = Dog("JIMMY", 1, 2, 3, "WOOF")
    print(id(obj))
    

提交回复
热议问题