user3509923
user3509923

Reputation: 33

Python 3 Inheritance

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

Upvotes: 1

Views: 536

Answers (2)

Lennart Regebro
Lennart Regebro

Reputation: 172179

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.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

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.

Upvotes: 2

Related Questions