Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python编写干代码_Python_Python 3.x_Dry - Fatal编程技术网

用Python编写干代码

用Python编写干代码,python,python-3.x,dry,Python,Python 3.x,Dry,我真的是一个新手,我正在重新编写战舰游戏,从Codecademy成为2名玩家。我真的很难通过这一次,但我觉得这是一个很好的锻炼,到目前为止。我想保持良好的OOP和DRY原则。不过我有个问题。我试图通过用户输入来创建对象,我必须创建两个类似的定义来实现我的目标。我只编写了程序的一部分,我已经尽可能多地进行了测试。要了解我的担忧,请查看下面的get_name1和get_name2: from random import randint class Person(object):

我真的是一个新手,我正在重新编写战舰游戏,从Codecademy成为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合并为一个函数,同时保留唯一的输入行“Player 1的名称是什么?”和“Player 2的名称是什么?”并将唯一的输入传递给两个不同的类对象?

所以这两个函数之间的唯一区别是Player number?然后将播放机号码作为参数传递给函数,并对提示使用字符串格式

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

通常,当您发现有两个几乎相同的函数时,您会查找不同之处,将其作为变量,并将变量作为参数传递。那么您只有一个函数可以通过其参数进行修改。

最好使用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)

您可能还希望将get_name()作为实例方法而不是类方法。首先,您可以在变量中编码播放器的编号(1/2)。Daniel,我最喜欢您的代码,因为create()方法比get_name()方法更干净。我只有一个问题:你是如何在方法中使用“cls”的?这类似于传递“自我”吗?另外,我在运行代码时也会遇到这个错误:Traceback(最近一次调用last):文件“C:\Users\KC\Documents\Programming\Python3\Battleship Game Two Player Build--OOP.py”,第21行,Player1=Person.create(“1”)TypeError:create()缺少1个必需的位置参数:“turn”类方法以类作为第一个参数隐式调用。与实例
self
类似,此参数名为
cls
。明白了。谢谢你的精心设计,现在可以用了。@classmethod似乎解决了这个问题。谢谢你帮助这个新手!