cheme_wilson
cheme_wilson

Reputation: 37

Class function returning 'None'

I am trying to learn class inheritance for OOP in python. The following code does what I want it to so far, but returns None after printing the pipe data when the function in the parent class is called. At first I didn't have the function returning the print statement, so I added in the return keyword, but that didn't get rid of the issue. I know it must be a return issue that I am overlooking. Any help would be appreciated.

import numpy as np


class piping:
    def __init__(self, diameter, length):
        self.d = diameter
        self.len = length

    def getPipeData(self):
        return print('The pipe length is %.1fm, and the diameter is %.1fm.' % (self.len, self.d))


class hydrodynamics(piping):
    def __init__(self, diameter, length, fluid, density):
        super().__init__(diameter, length)
        self.fluid = fluid
        self.density = density

        self.volume = self.getVolume()

    def getVolume(self):
        return np.pi*self.d**2/4


sec1 = hydrodynamics(1, 10, 'water', 1000)
sec2 = hydrodynamics(0.5, 30, 'water', 1000)

print(sec1.getPipeData())
print(sec2.getPipeData())
print(sec1.volume)
print(sec2.volume)

This is what is being returned...(as I said, everything works fine so far, except that I am having issues with the return None)

The pipe length is 10.0m, and the diameter is 1.0m.
None
The pipe length is 30.0m, and the diameter is 0.5m.
None
0.7853981633974483
0.19634954084936207

The output I was expecting is:

The pipe length is 10.0m, and the diameter is 1.0m.
The pipe length is 30.0m, and the diameter is 0.5m.
0.7853981633974483
0.19634954084936207

Upvotes: 1

Views: 8011

Answers (2)

quamrana
quamrana

Reputation: 39384

If that really is what you want from your program then you could change your calling code to this:

sec1.getPipeData()
sec2.getPipeData()
print(sec1.volume)
print(sec2.volume)

However, better is to not print anything inside member functions. If you change your class to the following, you can keep your driving code as is.

class piping:
    def __init__(self, diameter, length):
        self.d = diameter
        self.len = length

    def getPipeData(self):
        return 'The pipe length is %.1fm, and the diameter is %.1fm.' % (self.len, self.d)

Upvotes: 5

Alex G
Alex G

Reputation: 703

You should leave out the print statement in your definition of getPipeData and only return the string.

OR:

Call sec1.getPipeData() without the print, since the print will be executed when you call sec1.getPipeData()

Upvotes: 0

Related Questions