我真的很擅长开发,我正在从Codecademy重新编写Battleship游戏,成为2名玩家。我真的很难通过这个,但到目前为止,我觉得这是一个很好的练习。我想保持良好的OOP和DRY原则。不过我有一个问题。我试图传递用户输入来创建对象,我不得不创建两个类似的定义来实现我的目标。我只写了部分程序,并且我一直在测试。要查看我的问题,请查看下面的get_name1和get_name2:
from random import randint
class Person(object):
def __init__(self, name, turn):
self.name = name
self.turn = turn
def get_name1():
while 1:
name = input("What is the name of Player 1? ")
if name.isalpha() == False:
print("\nPlease share your name with me.\n")
else:
print("\nNice to meet you %s. It will be fun to play Battleship!\n" % name)
return name
break
def get_name2():
while 1:
name = input("What is the name of Player 2? ")
if name.isalpha() == False:
print("\nPlease share your name with me.\n")
else:
print("\nNice to meet you %s. It will be fun to play Battleship!\n" % name)
return name
break
Player1 = Person(Person.get_name1(), 1)
Player2 = Person(Person.get_name2(), 2)
print("Welcome to Battleship, %s!" % Player1.name)
print("You will take turn %s.\n" % Player1.turn)
print("Welcome to Battleship, %s!" % Player2.name)
print("You will take turn %s.\n" % Player2.turn)
有没有办法将get_name1和get_name2合并到一个函数中,同时保持&#34的唯一输入行;播放器1的名称是什么?"和#34;播放器2的名称是什么?"并仍然将唯一输入传递给两个不同的类对象?
答案 0 :(得分:3)
最好,使用classmethod创建一个名字的人:
class Person(object):
def __init__(self, name, turn):
self.name = name
self.turn = turn
@classmethod
def create(cls, turn):
while True:
name = input("What is the name of Player %d? " % turn)
if name.isalpha():
break;
print("\nPlease share your name with me.\n")
print("\nNice to meet you %s. It will be fun to play Battleship!\n" % name)
return cls(name, turn)
Player1 = Person.create(1)
Player2 = Person.create(2)
print("Welcome to Battleship, %s!" % Player1.name)
print("You will take turn %s.\n" % Player1.turn)
答案 1 :(得分:1)
def get_name(name_str):
while 1:
name = input("What is the name of %s? " % name_str)
if name.isalpha() == False:
print("\nPlease share your name with me.\n")
else:
print("\nNice to meet you %s. It will be fun to play Battleship!\n" % name)
return name
break
Player1 = Person(Person.get_name('Player 1'), 1)
Player2 = Person(Person.get_name('Player 2'), 2)
答案 2 :(得分:1)
所以两个功能之间的唯一区别是球员号码?然后将播放器编号作为参数传递给函数,并使用字符串格式化提示。
def get_name(player_number):
prompt = 'What is the name of Player {}? '.format(player_number)
while True:
name = input(prompt)
# rest of code goes here..
通常,当您发现两个函数几乎完全相同时,您会查找不同的函数,将其作为变量,并将变量作为参数传递。那么你只有一个函数可以被参数修改。