我试图建立一个在线MASH游戏。我如何输出:
print"欢迎使用程序{} {}" .format(self.first_name,self.last_name)如果没有输入中间名但是:
print"欢迎使用程序{} {} {}" .format(self.first_name,self.middle_name,self.last_name)如果输入了中间名:
类名称(对象):
def __init__(self, first_name='', last_name='', middle_name=''):
if not first_name:
first_name = raw_input("What is your first name: ")
if not last_name:
last_name = raw_input("What is your last name: ")
if not middle_name:
middle_name = raw_input("What is your middle name[Leave blank if not applicable]: ")
if middle_name == '':
print "No middle name here!"
self.first_name = first_name
self.last_name = last_name
self.middle_name = middle_name
self.print_name()
def print_name(self):
if not middle_name:
print "Welcome to the program {} {}".format(self.first_name, self.last_name)
else:
print "Welcome to the program {} {} {}".format(self.first_name,
self.middle_name,
self.last_name)
chris = Name()
答案 0 :(得分:0)
这似乎是你所描述的行为:
class Name (object):
def __init__(self, first_name, last_name, middle_name=None):
self.first_name = first_name
self.last_name = last_name
self.middle_name = middle_name
self.print_name()
def print_name(self):
if not self.middle_name:
print "Welcome to the program {} {}".format(self.first_name, self.last_name)
else:
print "Welcome to the program {} {} {}".format(self.first_name, self.middle_name, self.last_name)
chris_jones = Name(first_name='Chris', last_name='Jones')
chris_taylor_jones = Name(first_name='Chris', middle_name='Taylor', last_name='Jones')
注意我只在您的None
方法中添加了__init__()
参数。如果来电者未提供middle_name=None
参数,middle_name
会提供默认值。 This syntactic feature is called a "keyword argument"
输出:
Welcome to the program Chris Jones
Welcome to the program Chris Taylor Jones