[英]Returning variable vs. Setting variable
I'm considering the following approaches for class initialisation: 我正在考虑以下方法进行类初始化:
class Foo():
def __init__(self):
self.name = self.get_name()
def get_name(self):
return raw_input("Name: ")
class Foo():
def __init__(self):
self.name = ""
self.get_name()
def get_name(self):
self.name = raw_input("Name: ")
class Foo():
def __init__(self):
self.name = raw_input("Name: ")
Is there any practical reason to opt for one over the others? 是否有任何实际理由选择其中一个?
If not, which might be considered most Pythonic? 如果没有,哪个可能被认为是大多数Pythonic?
input()
the name outside of the class and pass it as a parameter to its __init__()
. input()
名称,并将其作为参数传递给__init__()
。 get_name()
to something like query_name()
or input_name()
. get_name()
重命名为query_name()
或input_name()
。 get_name()
sounds like a getter (that gets the value of name
) not like a setter or a routine that gets data from the user . get_name()
听起来像一个getter( 获取 name
的值),而不像setter或从用户 那里获取数据的例程。 I don't like the idea of doing a raw input in the constructor, but after all, why not... I would prefer: 我不喜欢在构造函数中执行原始输入的想法,但毕竟,为什么不...我更喜欢:
class Foo():
def __init__(self):
self.name = ""
def prompt_name(self):
self.name = raw_input("Name: ")
if __name__ == "__main__":
aFoo = Foo()
aFoo.prompt_name()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.