【问题标题】:How to return parent function value if it returns a value, and if not, continue running the child function?如果返回值,如何返回父函数值,如果没有,继续运行子函数?
【发布时间】: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


【解决方案1】:

我会这样做:

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
            

【讨论】:

  • 为什么要调用两次???
  • 因为我想将它体现在一个逻辑部分中,它与“颜色”参数一起使用,不要认为在这种情况下这种开销会破坏某些东西......
  • ...但是为什么不直接使用一个具有描述性名称的变量来表示结果呢?
猜你喜欢
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多