[英]Python Function Functionality
我正在冒险进入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?")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.