我正在冒险进入Python的奇妙世界!准确地说,是Python3。更准确地说,Python3.6?总之,我正在学习Python中的函数,我决定用Python编写一个函数,就像我知道如何编写函数一样,它起了作用!然而,我从未见过Python函数是这样编写的,在文档、书籍或互联网上的随机示例中都是如此。
所以,让我们拿一些小的东西,比如得到一个“玩家的名字”。
在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来说,我使用函数的方法是非常规的,还是我对它的理解不够深入,无法理解一种更流畅的代码编写方式。
有什么想法吗?
谢谢您抽时间见我!
发布于 2017-05-15 23:29:30
这种模式既不是好的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中没有按引用传递的选项。
发布于 2017-05-15 23:28:15
我想您可以在Python中压缩它,同时松散地维护您要使用的结构:
def _getPlayerName():
return input("What is the name?")
print("Hello, {0}!".format(_getPlayerName()))如果你喜欢的话,这也可以是一条线:
print("Hello, {0}!".format(input("What's your name?")))https://stackoverflow.com/questions/43990178
复制相似问题