Python, Overriding an inherited class method

前端 未结 5 2205
抹茶落季
抹茶落季 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:48

    Coming from a C++ perspective, there might be two misconceptions here.

    First, a method with the same name and different signature does not overload it like in C++. If one of your Background objects tries to call buildField with no arguments, the original version from Field will not be called -- it has been completely hidden.

    The second issue is that if a method defined in the superclass calls buildField, the subclass version will be called. In python, all methods are bound dynamically, like a C++ virtual method.

    Field's __init__ expected to be dealing with an object that had a buildField method taking no arguments. You used the method with an object that has a buildField method taking one argument.

    The thing with super is that it doesnt change the type of the object, so you shouldn't change the signature of any methods that the superclass' methods might call.

提交回复
热议问题