首页 > 解决方案 > 构造函数中没有默认参数,默认参数都在二维列表中

问题描述

我当前的代码:

WormModScratch.py

class WormMod:
    def __init__(self,wormColor, appleOrangeBananaPos = [[-1,-1],[0,0],[3,4]]):
        self.currentWormColor = wormColor
        self.appleOrangeBananaPos = appleOrangeBananaPos

    def say_hi(self):
        print(self.appleOrangeBananaPos[0][0])
        print(self.appleOrangeBananaPos[0][1])
        print(self.appleOrangeBananaPos[1][0])
        print(self.appleOrangeBananaPos[2][0])
        print(self.appleOrangeBananaPos[2][1])
        # print(self.orangePos[0], self.orangePos[1])

    def getHighScore(self):
        highscore_file = open("highscore.txt", "r")
        scorelist = highscore_file.readlines()
        highscore_file.close()
        return scorelist

测试2.py

from WormModScratch import WormMod

z = WormMod("blue")
z.say_hi()

print(z.getHighScore())

输出

-1
-1
0
3
4
['100\n', '50\n', '25\n']

------------------
(program exited with code: 0)
Press return to continue

我的问题:

def __init__(self,wormColor, appleOrangeBananaPos = [[-1,-1],[0,0],[3,4]]):

z = WormMod("blue")

我想让我的 2dList 中的第一个元素不默认,就像 [2],[0,0],[3,4]我想让它一样,所以 WormMod 必须包含两个苹果 xy 值,而其他两个水果默认为0,0and 3,4

z = WormMod("blue",[applex,appley])

如上所述,我如何完成两个非默认值和四个默认值?这只是我在 python 的第三周,我还在学习。

标签: python

解决方案


在调用该函数之前,您可以将 2d 数组拆分为 3 个列表,或者一开始就不要加入它们。然后,在函数内部,如果您需要将它们连接起来,您可以轻松地将它们再次连接在一起,从而允许您将其中的 2 个设置为默认值并保留一个作为要求。


推荐阅读