我正在冒险进入Python的奇妙世界!确切地说,是Python3。那么,更确切地说是Python 3.6?无论如何,我正在学习 Python 中的函数,我决定用 Python 编写一个函数,就像我知道如何编写函数一样,它奏效了!但是,我从未在文档中,书籍或互联网上的随机示例中看到过以这种方式编写的Python函数。
所以,让我们做一些小事,比如获得一个"玩家名字"。
在C++中,它将是这样的:
string getPlayerName(string playerName) {
output << "What is the name?";
input >> playerName;
return playerName;
}
当然,会有另一个函数(或不;))来显示PlayerName或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来说是否是非常规的,或者我是否不够深入,无法理解更流畅的代码编写方式。
有什么想法吗?
谢谢你的时间!
这种模式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 中没有按引用传递选项。
我想你可以在Python中将其压缩为这个,同时松散地维护你想要的结构:
def _getPlayerName():
return input("What is the name?")
print("Hello, {0}!".format(_getPlayerName()))
如果您愿意,这也可以在一行中:
print("Hello, {0}!".format(input("What's your name?")))