问题描述
我目前正在尝试学习 Python 并试图理解类,但我遇到了一个奇怪的问题。
class card:
def __init__(self,s,num,name):
self.suit = s
self.number = num
self.name = name
class aceCard(card):
def __init__(s):
card.__init__(s,"ace of " + s)
value1 = 1
valye11 = 11
class numCard(card):
def __init__(s,num):
name = num," of ",s
card.__init__(s,name)
value = num
class faceCard(card):
def __init__(s,num):
if (num == 11):
name = "jack of " + s
elif (num == 12):
name = "queen of " + s
elif (num == 13):
name = "king of " + s
card.__init__(s,name)
value = 10
class suits:
cards = []
def __init__(s):
cards = [aceCard.__init__(s)]
n = 1
while n<11:
cards.append(numCard.__init__(s,n))
n+=1
while n<14 and n>10:
cards.append(faceCard.__init__(s,n))
n+=1
class deck:
adeck = []
def __init__():
adeck = [suits.__init__("clubs"),suits.__init__("diamonds"),suits.__init__("hearts"),suits.__init__("spades")]
def print():
for suitses in adeck:
for cardses in suitses:
print(cardses.name)
deck1 = deck.__init__()
deck1.print()
来自 Spyder IDE 的错误消息是
runfile('###',wdir='###')
Traceback (most recent call last):
File "###",line 55,in <module>
deck1 = deck.__init__()
File "###",line 46,in __init__
adeck = [suits.__init__("clubs"),suits.__init__("spades")]
File "###",line 34,in __init__
cards = [aceCard.__init__(s)]
File "###",line 10,in __init__
card.__init__(s,"ace of " + s)
TypeError: __init__() missing 1 required positional argument: 'name'
让我困惑的部分是解释器希望 self 像普通参数一样使用而不是被跳过。请帮忙。
编辑: 我的问题似乎并没有被我搜索的任何东西解决。我的问题是,我正在检查教我的所有内容都告诉我将 self 作为参数使用,并且在代码中我将像 Java 中的“this”一样使用它。但是,当我调用构造函数时,我将忽略 self 作为第一个参数并仅使用后续参数。我遗漏了什么问题?
解决方法
您的代码有几个问题,但问题的根源在于您不知道如何构造父实例。
Python 使用 super()
来做到这一点:
class Card:
def __init__(self,s,num,name):
self.suit = s
self.number = num
self.name = name
class AceCard(Card):
def __init__(self,s):
super().__init__(s,"ace of " + s)
# This does nothing. Just creates local variables which are discarded
# once the function ends.
value1 = 1
valye11 = 11
我可以推荐 this tutorial 作为 Python 的 OOP 实现的一个很好的介绍。