我正在尝试检查父函数调用是否返回值,如果返回,则返回所述值。下面是一个例子:
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
但如果可能的话,我想找到一个更好的方法。
我会这样做:
class ParentClass():
@staticmethod
def some_function(color):
if (color == 'red'):
return 1
elif (color == 'blue'):
return 2
else:
#what happens if else?
return None
class ChildClass():
@staticmethod
def some_function(color):
t =ParentClass.some_function # personal preference
#t = super(ChildClass, ChildClass).some_function
if t(color) is not None:
return t(color)
elif (color == 'green'):
return 3
elif (color == 'yellow'):
return 4
else:
return None