简体   繁体   English

来自python函数的返回类型不一致 - 真的吗?

[英]Inconsistent return types from python functions – Really?

I am new to Python, but not new to programming. 我是Python新手,但不是编程新手。 To pick up on Python, I am going through an online introductory tutorial. 为了学习Python,我将学习在线入门教程。 I have worked through multiple examples of functions which return an inconsistent type of result, depending on arguments. 我已经研究了多个函数示例,这些函数根据参数返回不一致的结果类型。 EG, the result may be an integer or a boolean, as in by_three() in this example: EG,结果可以是整数或布尔值,如本例中的by_three():

def cube(number):
    return number**3

def by_three(number):
    if (number%3) == 0:
        return cube(number)
    else:
        return False

This sends up red flags to me. 这会给我发红旗。 Is this acceptable practice in the Python world? 这是Python世界中可接受的做法吗? Obviously the language allows it, it can be done, but should it be done? 显然语言允许它,它可以完成,但它应该完成吗?

I spent some time thinking about why python "allows" inconsistent return types and realized it is not just python, but pretty much any OO language. 我花了一些时间思考为什么python“允许”不一致的返回类型,并意识到它不仅仅是python,而是几乎任何OO语言。

In python everything is an object, even class definitions are objects. 在python中,一切都是对象,甚至类定义都是对象。 As far as I remember the only thing that is not an object is the type() function. 据我所知,唯一不是对象的是type()函数。

So we can now assume that all types have a topmost super type that every other type inherits from. 因此,我们现在可以假设所有类型都具有每个其他类型继承的最顶层超类型。 Like Object in Java. 就像Java中的Object一样。 Which leads me to this hypothetical Java code example where you have a service tier querying a repository for users with a specific last name 这引出了我这个假设的Java代码示例,其中您有一个服务层,用于查询具有特定姓氏的用户的存储库

Object getUsersByLastname(String lastname) {
    List<User> users = repository.getUsersByLastname(lastname);
    if (user.size() == 1) {
        return users.get(0);
    } else {
        return users;
    }
}

Anyone who has ever worked in Java will see this as a pretty poor piece of code. 任何曾经使用Java工作的人都会认为这是一段相当糟糕的代码。 Whatever is calling this will always have to do type checking before continuing. 无论调用什么,总是必须在继续之前进行类型检查。

My opinion is that the Python example shown above is also poor code and that you will end with a maintenance nightmare. 我的观点是,上面显示的Python示例也是糟糕的代码,您将以维护噩梦结束。 At the end of the day good design is something that is easy to maintain and does not require a ton of if... else... statements to work. 在一天结束时,良好的设计易于维护,并且不需要大量的if... else...语句。 It certainly feels like it break Open / Close principle in SOLID anyway, since at any time another return type can be added to that function and the calling code will need to be modified. 无论如何,它确实感觉它打破了SOLID中的Open / Close原则,因为在任何时候都可以向该函数添加另一个返回类型,并且需要修改调用代码。

Just because you can do something does not mean you should. 仅仅因为你可以做某事并不意味着你应该做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM