函数根据规则返回某个(对象或值)

时间:2013-05-11 23:55:13

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

假设我在python中有这个功能:

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

上述函数根据规则返回不同的值(int或string或object)。

我应该使用上述功能还是使用此功能:

def get_int()
    return 5

def get_string()
    return 'Hello'

def get_student()
    return Student()

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

在java中,您只能返回一种类型Ex:String only。

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

感谢。

编辑: 其他例子

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

1 个答案:

答案 0 :(得分:0)

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

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