【发布时间】:2018-07-02 14:49:55
【问题描述】:
我正在尝试在 python 中学习 OOP 的类继承。到目前为止,以下代码执行我想要的操作,但在调用父类中的函数时打印管道数据后返回 None 。起初我没有返回打印语句的函数,所以我添加了 return 关键字,但这并没有解决问题。我知道这一定是我忽略的退货问题。任何帮助,将不胜感激。
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)
这是返回的内容...(正如我所说,到目前为止一切正常,除了我在返回 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 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
【问题讨论】:
-
print返回None,您还期望它返回什么? -
@UnholySheep,你是什么意思? 'getPipeData' 返回的 'print' 语句将始终返回 'None'?
-
请使用您需要的代码输出更新您的问题。
-
print()的返回值始终为None。你从getPipeData()返回这个None -
@quamrana 我现在明白了!我只需要在代码末尾调用函数而不是打印函数。谢谢!