Force child class to override parent's methods











up vote
19
down vote

favorite
5












Suppose I have a base class with unimplemented methods as follows:



class Polygon():
def __init__(self):
pass

def perimeter(self):
pass

def area(self):
pass


Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows:



import math

class Circle(Polygon):
def __init__(self, radius):
self.radius = radius

def perimeter(self):
return 2 * math.pi * self.radius


(H/Sh)e has forgotten to implement the area() method.



How can I force the subclass to implement the parent's area() method?










share|improve this question


























    up vote
    19
    down vote

    favorite
    5












    Suppose I have a base class with unimplemented methods as follows:



    class Polygon():
    def __init__(self):
    pass

    def perimeter(self):
    pass

    def area(self):
    pass


    Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows:



    import math

    class Circle(Polygon):
    def __init__(self, radius):
    self.radius = radius

    def perimeter(self):
    return 2 * math.pi * self.radius


    (H/Sh)e has forgotten to implement the area() method.



    How can I force the subclass to implement the parent's area() method?










    share|improve this question
























      up vote
      19
      down vote

      favorite
      5









      up vote
      19
      down vote

      favorite
      5






      5





      Suppose I have a base class with unimplemented methods as follows:



      class Polygon():
      def __init__(self):
      pass

      def perimeter(self):
      pass

      def area(self):
      pass


      Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows:



      import math

      class Circle(Polygon):
      def __init__(self, radius):
      self.radius = radius

      def perimeter(self):
      return 2 * math.pi * self.radius


      (H/Sh)e has forgotten to implement the area() method.



      How can I force the subclass to implement the parent's area() method?










      share|improve this question













      Suppose I have a base class with unimplemented methods as follows:



      class Polygon():
      def __init__(self):
      pass

      def perimeter(self):
      pass

      def area(self):
      pass


      Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows:



      import math

      class Circle(Polygon):
      def __init__(self, radius):
      self.radius = radius

      def perimeter(self):
      return 2 * math.pi * self.radius


      (H/Sh)e has forgotten to implement the area() method.



      How can I force the subclass to implement the parent's area() method?







      python inheritance method-overriding






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 15 '17 at 20:08









      Aditya Barve

      32728




      32728
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          37
          down vote



          accepted










          this could be your parent class:



          class Polygon():
          def __init__(self):
          raise NotImplementedError

          def perimeter(self):
          raise NotImplementedError

          def area(self):
          raise NotImplementedError


          although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods.





          a different version is to use abc.abstractmethod.



          from abc import ABCMeta, abstractmethod
          import math

          class Polygon(metaclass=ABCMeta):

          @abstractmethod
          def __init__(self):
          pass

          @abstractmethod
          def perimeter(self):
          pass

          @abstractmethod
          def area(self):
          pass

          class Circle(Polygon):
          def __init__(self, radius):
          self.radius = radius

          def perimeter(self):
          return 2 * math.pi * self.radius

          # def area(self):
          # return math.pi * self.radius**2


          c = Circle(9.0)
          # TypeError: Can't instantiate abstract class Circle with abstract methods area


          you will not be able to instantiate a Circle without it having all the methods implemented.



          this is the python 3 syntax; in python 2 you'd need to



          class Polygon(object):
          __metaclass__ = ABCMeta




          also note that for the binary special functions __eq__(), __lt__(), __add__(), ... it is better to return NotImplemented instead of raising NotImplementedError.






          share|improve this answer






























            up vote
            3
            down vote













            That's exactly what NotImplementedError are used for :)



            In your base class



            def area(self):
            raise NotImplementedError("Hey, Don't forget to implement the area!"





            share|improve this answer




























              up vote
              2
              down vote













              You can raise NotImplementedError exception in base class method.



              class Polygon:
              def area(self):
              raise NotImplementedError


              Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44576167%2fforce-child-class-to-override-parents-methods%23new-answer', 'question_page');
                }
                );

                Post as a guest
































                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                37
                down vote



                accepted










                this could be your parent class:



                class Polygon():
                def __init__(self):
                raise NotImplementedError

                def perimeter(self):
                raise NotImplementedError

                def area(self):
                raise NotImplementedError


                although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods.





                a different version is to use abc.abstractmethod.



                from abc import ABCMeta, abstractmethod
                import math

                class Polygon(metaclass=ABCMeta):

                @abstractmethod
                def __init__(self):
                pass

                @abstractmethod
                def perimeter(self):
                pass

                @abstractmethod
                def area(self):
                pass

                class Circle(Polygon):
                def __init__(self, radius):
                self.radius = radius

                def perimeter(self):
                return 2 * math.pi * self.radius

                # def area(self):
                # return math.pi * self.radius**2


                c = Circle(9.0)
                # TypeError: Can't instantiate abstract class Circle with abstract methods area


                you will not be able to instantiate a Circle without it having all the methods implemented.



                this is the python 3 syntax; in python 2 you'd need to



                class Polygon(object):
                __metaclass__ = ABCMeta




                also note that for the binary special functions __eq__(), __lt__(), __add__(), ... it is better to return NotImplemented instead of raising NotImplementedError.






                share|improve this answer



























                  up vote
                  37
                  down vote



                  accepted










                  this could be your parent class:



                  class Polygon():
                  def __init__(self):
                  raise NotImplementedError

                  def perimeter(self):
                  raise NotImplementedError

                  def area(self):
                  raise NotImplementedError


                  although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods.





                  a different version is to use abc.abstractmethod.



                  from abc import ABCMeta, abstractmethod
                  import math

                  class Polygon(metaclass=ABCMeta):

                  @abstractmethod
                  def __init__(self):
                  pass

                  @abstractmethod
                  def perimeter(self):
                  pass

                  @abstractmethod
                  def area(self):
                  pass

                  class Circle(Polygon):
                  def __init__(self, radius):
                  self.radius = radius

                  def perimeter(self):
                  return 2 * math.pi * self.radius

                  # def area(self):
                  # return math.pi * self.radius**2


                  c = Circle(9.0)
                  # TypeError: Can't instantiate abstract class Circle with abstract methods area


                  you will not be able to instantiate a Circle without it having all the methods implemented.



                  this is the python 3 syntax; in python 2 you'd need to



                  class Polygon(object):
                  __metaclass__ = ABCMeta




                  also note that for the binary special functions __eq__(), __lt__(), __add__(), ... it is better to return NotImplemented instead of raising NotImplementedError.






                  share|improve this answer

























                    up vote
                    37
                    down vote



                    accepted







                    up vote
                    37
                    down vote



                    accepted






                    this could be your parent class:



                    class Polygon():
                    def __init__(self):
                    raise NotImplementedError

                    def perimeter(self):
                    raise NotImplementedError

                    def area(self):
                    raise NotImplementedError


                    although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods.





                    a different version is to use abc.abstractmethod.



                    from abc import ABCMeta, abstractmethod
                    import math

                    class Polygon(metaclass=ABCMeta):

                    @abstractmethod
                    def __init__(self):
                    pass

                    @abstractmethod
                    def perimeter(self):
                    pass

                    @abstractmethod
                    def area(self):
                    pass

                    class Circle(Polygon):
                    def __init__(self, radius):
                    self.radius = radius

                    def perimeter(self):
                    return 2 * math.pi * self.radius

                    # def area(self):
                    # return math.pi * self.radius**2


                    c = Circle(9.0)
                    # TypeError: Can't instantiate abstract class Circle with abstract methods area


                    you will not be able to instantiate a Circle without it having all the methods implemented.



                    this is the python 3 syntax; in python 2 you'd need to



                    class Polygon(object):
                    __metaclass__ = ABCMeta




                    also note that for the binary special functions __eq__(), __lt__(), __add__(), ... it is better to return NotImplemented instead of raising NotImplementedError.






                    share|improve this answer














                    this could be your parent class:



                    class Polygon():
                    def __init__(self):
                    raise NotImplementedError

                    def perimeter(self):
                    raise NotImplementedError

                    def area(self):
                    raise NotImplementedError


                    although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods.





                    a different version is to use abc.abstractmethod.



                    from abc import ABCMeta, abstractmethod
                    import math

                    class Polygon(metaclass=ABCMeta):

                    @abstractmethod
                    def __init__(self):
                    pass

                    @abstractmethod
                    def perimeter(self):
                    pass

                    @abstractmethod
                    def area(self):
                    pass

                    class Circle(Polygon):
                    def __init__(self, radius):
                    self.radius = radius

                    def perimeter(self):
                    return 2 * math.pi * self.radius

                    # def area(self):
                    # return math.pi * self.radius**2


                    c = Circle(9.0)
                    # TypeError: Can't instantiate abstract class Circle with abstract methods area


                    you will not be able to instantiate a Circle without it having all the methods implemented.



                    this is the python 3 syntax; in python 2 you'd need to



                    class Polygon(object):
                    __metaclass__ = ABCMeta




                    also note that for the binary special functions __eq__(), __lt__(), __add__(), ... it is better to return NotImplemented instead of raising NotImplementedError.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 7 at 6:24

























                    answered Jun 15 '17 at 20:12









                    hiro protagonist

                    17.3k63560




                    17.3k63560
























                        up vote
                        3
                        down vote













                        That's exactly what NotImplementedError are used for :)



                        In your base class



                        def area(self):
                        raise NotImplementedError("Hey, Don't forget to implement the area!"





                        share|improve this answer

























                          up vote
                          3
                          down vote













                          That's exactly what NotImplementedError are used for :)



                          In your base class



                          def area(self):
                          raise NotImplementedError("Hey, Don't forget to implement the area!"





                          share|improve this answer























                            up vote
                            3
                            down vote










                            up vote
                            3
                            down vote









                            That's exactly what NotImplementedError are used for :)



                            In your base class



                            def area(self):
                            raise NotImplementedError("Hey, Don't forget to implement the area!"





                            share|improve this answer












                            That's exactly what NotImplementedError are used for :)



                            In your base class



                            def area(self):
                            raise NotImplementedError("Hey, Don't forget to implement the area!"






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jun 15 '17 at 20:11









                            Bubble Bubble Bubble Gut

                            1,899618




                            1,899618






















                                up vote
                                2
                                down vote













                                You can raise NotImplementedError exception in base class method.



                                class Polygon:
                                def area(self):
                                raise NotImplementedError


                                Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module






                                share|improve this answer



























                                  up vote
                                  2
                                  down vote













                                  You can raise NotImplementedError exception in base class method.



                                  class Polygon:
                                  def area(self):
                                  raise NotImplementedError


                                  Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module






                                  share|improve this answer

























                                    up vote
                                    2
                                    down vote










                                    up vote
                                    2
                                    down vote









                                    You can raise NotImplementedError exception in base class method.



                                    class Polygon:
                                    def area(self):
                                    raise NotImplementedError


                                    Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module






                                    share|improve this answer














                                    You can raise NotImplementedError exception in base class method.



                                    class Polygon:
                                    def area(self):
                                    raise NotImplementedError


                                    Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jun 15 '17 at 20:18

























                                    answered Jun 15 '17 at 20:11









                                    vishes_shell

                                    9,48823345




                                    9,48823345






























                                         

                                        draft saved


                                        draft discarded



















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44576167%2fforce-child-class-to-override-parents-methods%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest




















































































                                        Popular posts from this blog

                                        横浜市

                                        Rostock

                                        Europa