Python 函数功能

Python Function Functionality

我正在冒险进入Python的精彩世界! Python3,确切地说。好吧,Python 3.6 更准确些?无论如何,我正在学习 Python 中的函数,我决定按照我知道如何编写函数的方式在 Python 中编写一个函数,并且成功了!但是,我从未在文档、书籍或 Internet 上的随机示例中见过以这种方式编写的 Python 函数。

所以,让我们做点小事,比如 "player name"。

在 C++ 中,它类似于:

string getPlayerName(string playerName) {
    output << "What is the name?";
    input >> playerName;

    return playerName;
}

当然,displayPlayerName 或 showPlayerName 会有另一个函数(或没有 ;)),但您必须初始化函数变量:

void displayPlayerName() {
    string playerNameFunction = "";
    string playerNamePlaceHolder = "";

    playerNameFunction = getPlayerName(playerNamePlaceHolder);

    output << "Hello, " << playerNameFunction << "!" << endl;
}

现在,在 Python,我从未见过这样的事情。在我见过的所有示例中,我已经看到变量在哪里更硬编码。

def _getAge(age):
    print("How old are you?")
    print(age)

_getAge(30)

但是!如果我们使用 C++ 示例,它在 Python 中有效并且看起来完全合法和合乎逻辑!

def _getPlayerName(playerName):
    playerName = input("What is the name?")

    return playerName

playerNameFunction = ""
playerNamePlaceHolder = ""

playerNameFunction = _getPlayerName(playerNamePlaceHolder)
print("Hello, " + playerNameFunction + "!")

现在,我知道这可能看起来像废话,而且我知道这一切的漫长曲折可能会破坏 Python 的目的。但我很想知道我使用函数的方法是否对 Python 来说是非常规的,或者我是否只是不够深入以理解更流畅的代码编写方式。

有什么想法吗?

感谢您的宝贵时间!

我想你可以在 Python 中将它压缩成这样,同时松散地维护你想要的结构:

def _getPlayerName():
    return input("What is the name?")

print("Hello, {0}!".format(_getPlayerName()))

如果你愿意,这也可以全部放在一行中:

print("Hello, {0}!".format(input("What's your name?")))

这个模式不是很好的 C++ 或 Python。 playerName 争论毫无意义。

在 C++ 中,您应该写成

string getPlayerName() {
    string playerName;

    output << "What is the name?";
    input >> playerName;

    return playerName;
}

并将其命名为

string playerName = getPlayerName();

而不是从调用者那里不必要地复制一个占位符值然后覆盖它,或者

void getPlayerName(string& playerName) {
    output << "What is the name?";
    input >> playerName;
}

并将其命名为

string playerName;
getPlayerName(playerName);

将玩家名称直接读取到通过引用传递的字符串中。


在Python中,你应该写

def getplayername():
    return input("What is the name?")

Python 中没有传递引用选项。