简体   繁体   English

Python'object()不带参数'错误

[英]Python 'object() takes no parameters' error

I have the class parameter below which should return the index of 2 numbers within the 'nums' list that sums up to the target. 我有下面的类参数,它应该返回“ nums”列表中2个数字的索引,这些数字加总到目标。

When I tried to test the class using 9 as the target by writing 'Solution(nums,9)', Python returned the 'TypeError: object() takes no parameters' error. 当我尝试通过编写'Solution(nums,9)'将9作为目标来测试类时,Python返回了'TypeError:object()不带参数'错误。 Can anyone advise me on what I did wrong in my script? 谁能告诉我我在脚本中做错了什么?

nums = [2, 7, 11, 15]
class Solution(object):
    def twoSum(self, nums, target):
        nums_1 = nums        
        for i in range(len(nums)):
            for a in range(len(nums_1)):
                if i != a:
                    if nums[i] + nums_1[a] == target:
                        return(sorted([i, a]))
Solution(nums,9)

Traceback (most recent call last):
TypeError: object() takes no parameters

You can't use it like that, because your class have default __init__(which your class get by default, since you didn't define it), and it doesn't take any parameters unless you define it to take it. 您不能那样使用它,因为您的类具有默认的__init __(由于您未定义它,因此该类在默认情况下会得到它),并且除非您定义要接受的参数,否则它不会接受任何参数。

Use the following: 使用以下内容:

sol = Solution()
sorted_stuff = sol.twoSum(nums, 9)
print(sorted_stuff)

You have missed the __init__() method while defining your Solution class. 您在定义解决方案类时错过了__init__()方法。 Its not always compulsory, but since you are creating an instance of the class by calling Solution() with some arguments, the __init__ method must be implemented. 它并不总是强制性的,但是由于您是通过使用一些参数调用Solution()创建类的实例的,因此必须实现__init__方法。 So the implementation can be: 因此实现可以是:

_nums = [2, 7, 11, 15]
class Solution(object):
    def __init(nums, target):
      self.nums = nums
      self.target = target

    def twoSum(self, nums=None, target=None):
        if not nums:
           nums = self.nums

        if not target:
           target= self.target

        nums_1 = nums        
        for i in range(len(nums)):
            for a in range(len(nums_1)):
                if i != a:
                    if nums[i] + nums_1[a] == target:
                        return(sorted([i, a]))
s = Solution(_nums,9)
s.twoSum()

Also you can do: 您也可以执行以下操作:

 s = Solution()
 s.twoSum(_nums,9)

This gives you the freedom to either have the args defined during the class initialization or calling the actual method with the args. 这使您可以自由地在类初始化期间定义args或使用args调用实际方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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