Python 상속 : TypeError : object .__ init __ ()에는 매개 변수가 없습니다.


92

이 오류가 발생합니다.

TypeError: object.__init__() takes no parameters 

내 코드를 실행할 때 나는 여기서 내가 뭘 잘못하고 있는지 실제로 보지 못합니다.

class IRCReplyModule(object):

    activated=True
    moduleHandlerResultList=None
    moduleHandlerCommandlist=None
    modulename=""

    def __init__(self,modulename):
        self.modulename = modulename


class SimpleHelloWorld(IRCReplyModule):

     def __init__(self):
            super(IRCReplyModule,self).__init__('hello world')

답변:


117

super () 호출에서 잘못된 클래스 이름을 호출하고 있습니다.

class SimpleHelloWorld(IRCReplyModule):

     def __init__(self):
            #super(IRCReplyModule,self).__init__('hello world')
            super(SimpleHelloWorld,self).__init__('hello world')

본질적으로 해결하려는 것은 __init__매개 변수를 사용하지 않는 객체 기본 클래스입니다.

이미 알고있는 클래스를 지정해야하는 것은 약간 중복되므로 python3에서 다음을 수행 할 수 있습니다. super().__init__()


4
@LucasKauffman : 사실 나는 당신이 매우 어리 석다고 생각하지 않습니다. 그것은 쉽게 혼란스러운 개념이 될 수 있습니다. 당신을 비난하지 않습니다.
jdi

4
많은 Pythonian을 불쾌하게 할 위험에 처해 있습니다. 즉, imho는 끔찍한 언어 설계입니다. @jdi의 도움에 감사드립니다!
Johannes Fahrenkrug 2015-04-29


3

이것은 최근에 두 번 저를 물었습니다 (처음에는 실수에서 배웠어야한다는 것을 알고 있습니다) 그리고 받아 들여진 대답은 두 번도 저에게 도움이되지 않았으므로 내 마음에는 신선하지만 경우에 대비하여 제 대답을 제출할 것이라고 생각했습니다. 다른 사람이이 문제를 겪고 있습니다 (또는 나중에 다시 필요합니다).

제 경우 문제는 하위 클래스의 초기화에 kwarg를 전달했지만 수퍼 클래스에서 해당 키워드 arg가 super () 호출에 전달된다는 것입니다.

나는 항상 이러한 유형의 것이 가장 좋다고 생각합니다.

class Foo(object):
  def __init__(self, required_param_1, *args, **kwargs):
    super(Foo, self).__init__(*args, **kwargs)
    self.required_param = required_param_1
    self.some_named_optional_param = kwargs.pop('named_optional_param', None)

  def some_other_method(self):
    raise NotImplementedException

class Bar(Foo):
  def some_other_method(self):
    print('Do some magic')


Bar(42) # no error
Bar(42, named_optional_param={'xyz': 123}) # raises TypeError: object.__init__() takes no parameters

이 문제를 해결하려면 Foo .__ init__ 메서드에서 수행하는 순서를 변경하면됩니다. 예 :

class Foo(object):
  def __init__(self, required_param_1, *args, **kwargs):
    self.some_named_optional_param = kwargs.pop('named_optional_param', None)
    # call super only AFTER poping the kwargs
    super(Foo, self).__init__(*args, **kwargs)
    self.required_param = required_param_1
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.