Using raw input inside of a class (python 2.7)
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')
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).
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()
链接地址: http://www.djcxy.com/p/54286.html
上一篇: 爬虫类方法的工作?