1

I'm a bit of a beginner with OOP and have been trying to teach myself some of its concepts using Python3. However, I have gotten stuck with inheritance. This is my source code:

#! /usr/bin/env python3

class TwoD:
    def __init__(self, height, width):
    self.h = height
    self.w = width
def perimeter(self, height, width):
    return 2 * (height + width)
def area(self, height, width):
    return height * width

class Cuboid(TwoD):
def __init__(self, height, width, depth):
    self.d = depth
def volume(self, height, width, depth):
    return height * width * depth

x = Cuboid(3, 4, 5)
print(x.volume())
print(x.perimeter())
print(x.area())

The error I get when I run it is below. It reads as though I need to add arguments to volume, but doesn't x provide it with the required variables?

Traceback (most recent call last):
File "./Class.py", line 19, in <module>
print(x.volume())
TypeError: volume() missing 3 required positional arguments: 'height', 'width', and 'depth'

So could someone please let me know what I am doing wrong. I'm sure it is something silly. Also, could someone please explain how I would go about using multiple inheritance in Python3?

Thanks in advance

1
  • Replace all your tabs with 4 spaces, please. Commented Apr 15, 2014 at 20:02

2 Answers 2

2

Since in the __init__() method you are creating two data attributes self.h and self.w, you can use them in your other methods, so it's not necessary to pass any arguments:

def perimeter(self):
    return 2 * (self.h + self.w)

def area(self):
    return self.h * self.w

Also, in the __init__() method of the Cuboid class don't forget to call super, so self.h and self.w become data attributes.

Sign up to request clarification or add additional context in comments.

Comments

1

It reads as though I need to add arguments to volume, but doesn't x provide it with the required variables?

Yes, it does, which means you should not have them in the method definition at all:

class TwoD:
    def __init__(self, height, width):
        self.h = height
        self.w = width
    def perimeter(self):
        return 2 * (self.h + self.w)
    def area(self):
        return self.h * self.w

Etcetera. So in fact it's not inheritance which is the problem, but that your code was not object oriented at all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.