0

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?

4
  • 11
    I wouldn't use a raw_input() inside an object though, but thats just me. Move it outside and supply the name when constructing your object. Commented Apr 24, 2013 at 12:35
  • Approach #2 is essentially the same as #1. Commented Apr 24, 2013 at 12:41
  • So basically you're asking what's the best way to design a class Foo? Well, I guess the most pythonic would be bar, although baz can make sense too, if not quux. Commented Apr 24, 2013 at 12:46
  • I should've gone for Spam. Nobody ever questions Spam. Commented Apr 24, 2013 at 13:02

2 Answers 2

2
  • 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.
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Why not? Because application logic should be separated from getting input. (If this is possible.)
get_name should return name, because it looks like a getter.
+1 soon, agree that the method name is not my primary choice... Fixed in edit :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.