Python, Overriding an inherited class method

前端 未结 5 2208
抹茶落季
抹茶落季 2020-12-23 01:58

I have two classes, Field and Background. They look a little bit like this:

class Field( object ):
    def __init__( self, a, b ):
         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 02:37

    I expected Background init() to be called

    Actually Background init() is getting called..

    But take a look at your Background class..

    class Background( Field ):
        def __init__( self, a, b, c ):
            super(Background, self).__init__( a, b )
            self.field = self.buildField( c )
    

    So, the first statement of __init__ is invoking the super class(Field) init method.. and passing the self as argument.. Now this self is actually a reference of Background class..

    Now in your Field class: -

    class Field( object ):
        def __init__( self, a, b ):
    
            print self.__class__  // Prints ``
            self.a = a
            self.b = b
            self.field = self.buildField()
    

    Your buildField() method is actually invoking the one in the Background class.. This is because, the self here is instance of Background class(Try printing self.__class__ in your __init__ method of Field class).. As you passed it while invoking the __init__ method, from Background class..

    That's why you are getting error..

    The error "TypeError: buildField() takes exactly 2 arguments (1 given).

    As you are not passing any value.. So, only value passed is the implicit self.

提交回复
热议问题