简体   繁体   中英

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?

  • If possible, input() the name outside of the class and pass it as a parameter to its __init__() .
  • If this is not an option, I would go for the second alternative
  • I would rename get_name() to something like query_name() or 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 .

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM