【问题标题】:a function returns a certain (object or value) based on a rule函数根据规则返回某个(对象或值)
【发布时间】:2013-05-06 08:29:33
【问题描述】:

假设我在 python 中有这个函数:

def get_thing(rule):
    if rule == 0:
        return 5         #<<<< int
    elif rule == 1:
        return 'Hello'   #<<<<< string
    else:
        return Student() #<<<<< Object

上述函数根据规则返回不同的值(int或字符串或对象)。

我应该使用上面的函数还是使用这个函数:

def get_int()
    return 5

def get_string()
    return 'Hello'

def get_student()
    return Student()

我的意思是函数返回不同的数据类型或值是 Pythonic 吗?

在 java 中你只能返回一种类型,例如:String only。

希望你能理解我的问题:)

谢谢。

编辑: 其他例子

def get_person(id):
    if #id is belongs to student:
        return Student()
    elif #id belongs to teacher
        return Teacher()

【问题讨论】:

  • 你需要它做什么?
  • 我认为您将不得不为这个问题提供更多背景信息。话虽如此,第一个 sn-p 看起来并不是一个好的解决方案。

标签: python oop python-2.7 python-3.x uml


【解决方案1】:

可以从 Python 中的函数返回不同类型的值。就实现而言,考虑使用字典而不是嵌套的 if,例如:

def get_thing(rule):
    return { 0 : 5, 1 : 'Hello'}.get(rule, Student())

【讨论】:

  • 从某种意义上说 Python 允许这样做是可以的,但这不是维护的好习惯。请参阅上面评论中的 PartiallyFinite 链接。
  • 视情况而定。有很多情况是绝对没问题的。 Python 之所以会打字是有原因的。
  • 你给出的最后一个例子就是一个很好的例子。如果Student和Teacher都有一个共同的基类(Person),即使在静态类型语言(如C++或Java)中,也可以从函数中返回Student和Teacher,这确实是一个很好的OO设计。
  • 如果它们不是从类 Person 继承的呢?
  • 那么如果他们共享一个共同的行为(具有相同的外观方法或属性)就可以了,这就是我们所说的鸭子类型。即使它只能被打印/转换为字符串,无论您从该函数返回的内容是什么。
猜你喜欢
  • 2019-02-09
  • 2019-10-27
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2021-10-26
  • 2018-06-14
相关资源
最近更新 更多