【发布时间】:2022-01-12 21:47:02
【问题描述】:
我正在尝试检查父函数调用是否返回值,如果返回,则返回所述值。下面是一个例子:
class ParentClass():
@staticmethod
def some_function(color):
if (color == 'red'):
return 1
elif (color == 'blue'):
return 2
class ChildClass()
@staticmethod
def some_function(color):
super(ChildClass, ChildClass).some_function(color)
if (color == 'green'):
return 3
elif (color == 'yellow'):
return 4
如果函数调用 super(ChildClass, ChildClass).some_function(color) 返回任何值,我想返回该值,但如果没有,请继续 ChildClass 的 some_function 中的其余代码。
我目前的解决方案是将父函数调用替换为:
super_value = super(ChildClass, ChildClass).some_function(color)
if super_value:
return super_value
但如果可能的话,我想找到一种更好的方法。
【问题讨论】:
-
您的解决方案与合理需要的差不多。如果您想返回 0,可能会将 if super_value 更改为显式 == None 语句
-
请注意,如果它是
0,您的解决方案将不会返回超值。如果要检查它是否返回值,请使用if super_value is not None: -
“但如果可能的话,我想找到一个更好的方法来做到这一点。” 以什么方式更好?
-
我想出了另一个可行的解决方案,不管是先调用父函数还是子函数。我从函数顶部删除了父调用,并在末尾添加了
else: return super(ChildClass, ChildClass).some_function(color)。
标签: python python-3.x function inheritance