-2

I was wondering how to use raw input inside of a class, so instead of passing the name 'Ryan' we could pass a variable inside of the object and ask for that variable later on.

such as:

name = raw_input("What is your name? ")

Here is the code I have:

class Talk:
        def __init__(self, name):
                self.name = name
                print "Hey there, " + self.name

        def printName(self):
                print self.name

talk = Talk('Ryan')
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 3
    Can you be a little clearer about what you want? Post the relevant code in the question and give some example input/output – khelwood Jan 19 '15 at 17:04

2 Answers2

3

Typically, this would be done with a class method, separating the user input (and any associated validation) from the __init__ of the new instance:

class Talk(object):

    def __init__(self, name):
        self.name = name
        print "Hey there, {}".format(self.name)

    def print_name(self):
        print self.name

    @classmethod
    def from_input(cls):
        """Create a new Talk instance from user input."""
        while True:
            name = raw_input("Enter your name: ")
            if name:
                return cls(name)

Which would be used like:

>>> talk = Talk.from_input()
Enter your name: Ryan
Hey there, Ryan
>>> talk.print_name()
Ryan

Note that I have renamed printName to print_name, per the style guide. Also, it would be conventional to not print from inside __init__, and provide __str__ and __repr__ methods rather than a print_name (see Python's data model documentation for more information).

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

You can call functions inside class methods. These methods include __init__. For example:

class Talk:
    def __init__(self):
        self.name = raw_input("What is your name: ")
        print "Hey there, " + self.name

    def printName(self):
        print self.name

talk = Talk()
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173