Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Inheritance problem
#5
Overwriting is not the right term in this case. Your geometry class inherits from two classes that both have a "surface" method. When calling geometry.surface() which method is used? In your case it uses sphere.surface() because Sphere appears first in
class geometry(sphere,cube):. The geometry.mro() would show the order.

I don't think you want geometry to be a subclass of sphere and cube. Instead I think you want it to be their superclass. Inheritence should be from the generic to the specific. The superclass of sphere should be more generic than a sphere.
import math

class geometry:
    """base class for geometetric shapes"""
    def surface(self):
        """Return surface area"""
        raise NotImplementedError('Subclass responsibility')

class sphere(geometry):
    def __init__(self, radius):
        self.radius = radius

    def surface(self):
        return 4 * math.pi * self.radius * self.radius

class cube(geometry):
    def __init__(self, edge):
        self.edge = edge

    def surface(self):
        return 6 * self.edge * self.edge

shapes = [sphere(3), cube(3), cube(5), sphere(6)]

for shape in shapes:
    print(shape.surface())
Reply


Messages In This Thread
Inheritance problem - by DPaul - May-05-2020, 10:04 AM
RE: Inheritance problem - by buran - May-05-2020, 11:34 AM
RE: Inheritance problem - by DPaul - May-05-2020, 03:01 PM
RE: Inheritance problem - by buran - May-05-2020, 03:46 PM
RE: Inheritance problem - by deanhystad - May-05-2020, 04:01 PM
RE: Inheritance problem - by buran - May-05-2020, 04:08 PM
RE: Inheritance problem - by DPaul - May-05-2020, 04:14 PM
RE: Inheritance problem - by buran - May-05-2020, 04:22 PM
RE: Inheritance problem - by deanhystad - May-05-2020, 04:42 PM
RE: Inheritance problem - by DPaul - May-05-2020, 05:46 PM
RE: Inheritance problem - by buran - May-05-2020, 06:37 PM
RE: Inheritance problem - by deanhystad - May-05-2020, 08:13 PM
RE: Inheritance problem - by DPaul - May-06-2020, 06:35 AM
RE: Inheritance problem - by buran - May-06-2020, 06:44 AM
RE: Inheritance problem - by DPaul - May-06-2020, 07:38 AM
RE: Inheritance problem - by buran - May-06-2020, 07:46 AM
RE: Inheritance problem - by DPaul - May-06-2020, 05:30 PM
RE: Inheritance problem - by buran - May-06-2020, 05:35 PM
RE: Inheritance problem - by DPaul - May-07-2020, 10:13 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Inheritance problem Maryan 0 1,331 Oct-25-2020, 02:39 PM
Last Post: Maryan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020