python - 构造函数中没有默认参数,默认参数都在二维列表中
问题描述
我当前的代码:
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,0
and 3,4
。
z = WormMod("blue",[applex,appley])
如上所述,我如何完成两个非默认值和四个默认值?这只是我在 python 的第三周,我还在学习。
解决方案
在调用该函数之前,您可以将 2d 数组拆分为 3 个列表,或者一开始就不要加入它们。然后,在函数内部,如果您需要将它们连接起来,您可以轻松地将它们再次连接在一起,从而允许您将其中的 2 个设置为默认值并保留一个作为要求。
推荐阅读
- date - 如何在预填充输入字段并使用 jquery inputmask 插件对其进行屏蔽时停止向左移动字符?
- sql - 从行创建逗号分隔的组列表
- javascript - 在新选项卡中打开文件
- cmake - cmake find_library()找不到PATHS指定的库
- json - 处理 Angular Proxy 404 [预期] 错误
- python - 生成非二元贝叶斯网络时出错
- css - CSS Flexbox 使中心项目真正居中
- javafx - 树莓派 4 上的胶子 javafx
- python - 您可以使用 namedtuples/dataclass/attrs 创建一个灵活大小的类还是必须使用传统类?
- java - 为什么我会收到“由于缺少'需要传递'而导致客户端无法访问模块 javafx.graphics 的类型 GraphicsContext”警告?