我正在努力第一次创建一个类,我在这里和那里遇到困难,首先阅读我的代码,然后我会在它之后发布错误
import random
class card_deck:
suites= ["Clubs", "Diamonds", "Hearts", "Spades"]
ranks= ["Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"]
def __init__(self, rank, suite, card):
self.rank= rank
self.suite = suite
self.card = card
def card_list(self):
suites= ["Clubs", "Diamonds", "Hearts", "Spades"]
ranks= ["Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"]
def ranks(self):
return self.rank
def suite(self):
return self.suite
def card(self,card):
return self.card
def __str__(self):
return (Card.ranks[self.rank],
Card.suits[self.suit])
def value(self):
if self.rank == 'Ace':
return 1
elif self.rank == 'Jack':
return 11
elif self.rank == 'Queen':
return 12
elif self.rank == 'King':
return 13
def shffule(self):
random.shuffle(self.card)
def remove(self,card):
self.card.remove(card)
def __getitem__(self,i):
return self.card_list()
def append(self,value):
super(card_deck,self).append(value)
return self
def cardremaining(self):
self.suite-self.rank
def main():
try:
rank = []
suite = []
card = []
deck = card_deck(rank,suite,card)
deck.shffule()
#drup=[]
for i in ['Spades','Hearts', ' Diamonds','Clubs']:
for c in ['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King']:
deck.append([c, i])
hand = []
user =eval(input('Enter a number of cards: 1-7 '))
print()
while user <1 or user >7:
print ("Only a number between 1-7:")
return main()
for i in range(user):
hand.append(deck[i])
print(hand)
except ValueError:
print("Only numbers")
main()
这是我运行main()
时得到的结果 Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
main() File "/Users/user/Desktop/deck_class.py", line 66, in main
deck.append([c, i])
File "/Users/user/Desktop/deck_class.py", line 44, in append
super(card_deck,self).append(value)
AttributeError: 'super' object has no attribute 'append'
所以即使我尝试删除super并且只是写了slef.append(value)我得到了另一个错误,python继续打印
File "/Users/user/Desktop/deck_class.py", line 44, in append
card_deck,self.append(value)
File "/Users/user/Desktop/deck_class.py", line 44, in append
我在发布问题之前做过研究,我试图修复自己,但这对我来说感觉太复杂了,我希望你们能帮忙!我做错了什么?
谢谢
答案 0 :(得分:1)
我的印象是您正在尝试将假装的card_deck
对象作为某种列表。我也觉得你试图让你的card_deck
对象扮演两个独立的角色:一副牌和一张牌。
考虑到这一点,退一步,将代码分成两个单独的类并执行类似下面的操作会简单得多。我在代码中留下了评论来解释我的思考过程:
import random
class Card(object):
'''Remember, a 'card' is completely different from a deck. You can have a
card that is not contained in a deck, and a deck is simply another object
that contains one or more cards, with a few convenience methods attached.'''
def __init__(self, rank, suite):
self.rank = rank
self.suite = suite
def __repr__(self):
'''The different between '__repr__' and '__str__' is not particularly
important right now. You can google the difference yourself.'''
return "Card({0}, {1})".format(self.rank, self.suite)
def __str__(self):
return "{0} of {1}".format(self.rank, self.suite)
def value(self):
ranks = ["Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"]
# This is something called a 'dictionary comprehension'. It lets you
# map the rank of the card to its corresponding value.
#
# 'enumerate' is a built-in. Try doing `enumerate(["a", "b", "c", "d"])`
# in the shell, and see what happens.
values = {rank: i + 1 for (i, rank) in enumerate(ranks)}
return values[self.rank]
class Deck(object):
'''Now, we have the deck.'''
def __init__(self):
self.suites = ["Clubs", "Diamonds", "Hearts", "Spades"]
self.ranks = ["Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"]
# Here, I've chosen to create a full deck when instantiating the object.
# You may chose to modify your code to pass in the cards you want instead.
#
# Notice how we're keeping track of all of our cards inside of a list.
# This way, we're free to write whatever methods we want, while still
# internally representing our deck of cards in the cleanest manner possible.
self.cards = []
for suite in self.suites:
for rank in self.ranks:
self.cards.append(Card(suite, rank))
def shuffle(self):
random.shuffle(self.cards)
def remove(self, card):
# idk if this will actually work -- you should test it.
self.cards.remove(card)
def append(self, card):
'''In this method, we're taking a card, and adding it to our deck.
We've written the entire thing ourselves -- no need to call to super
(which doesn't work, in any case)'''
self.cards.append(card)
def get_top_card(self):
'''This is a common operation when dealing with decks -- why not add it?'''
return self.cards.pop()
def __repr__(self):
return "[" + ", ".join(repr(card) for card in self.cards) + "]"
def __str__(self):
return '\n'.join(str(card) for card in self.cards)
def main():
deck = Deck()
deck.shuffle()
hand = []
while True:
user = int(input('Enter a number of cards: 1-7 '))
print()
if not 1 <= user <= 7:
print ("Only a number between 1-7:")
else:
break
for i in range(user):
hand.append(deck.get_top_card())
print(hand)
if __name__ == '__main__':
main()
现在,您可能想知道super(card_deck,self).append(value)
在原始示例中实际执行了什么操作。调用super(card_deck, self)
将返回card_deck
类的父类 - 换句话说,类card_deck
继承自。{/ p>
在这种情况下,你的类不继承任何东西(从技术上讲,它继承了内置的“object”类,但是每个类都继承自object
,所以这没有实际意义。)
然后,当您致电append
时,您正试图调用append
父类中存在的card_deck
方法。但是,不存在这样的方法,因此您的代码会抛出异常。
在你的情况下,由于你刚刚开始使用类,我强烈建议你暂时忽略继承和'超级'内置函数。它太过分了,当你试图抓住面向对象的编程时,它只会让你感到困惑。而是集中精力编写好的对象,提供操作自己定义的变量的好方法。
答案 1 :(得分:1)
你真的知道super()的意思吗? super可以从当前类继承的类中调用该函数。即:
class card_deck(list):
....
super(..).append(...)
....
您的脚本中也存在一些错误
def __getitem__(self,i):
return self.card_list()
实际上你不在函数中使用i。
如果这是你第一次写一个类而且你是python的新手。我建议你从一些简单的课程开始,尝试使用简单的功能来实现你的目标。你不需要使用__getitem__
或super()
。如果没有正确理解,他们会让你感到困惑。