在实验过程中,我遇到了一个非常奇怪的问题让我非常困惑。通过迭代一个范围创建几个类对象后,我从另一个类调用了一个函数,该函数将1个字符串附加到主类对象。在查看了所有对象的列表之后,我看到它们都是相同的,即使它们应该是不同的,并且每个类不只有一个字符串,但是字符串的数量与类对象本身。
class Stack():
cards = []
setUp = False
def set_up(self):
cardTypes = ["A", "B", "C", "D"]
for cardType in cardTypes:
for x in range(3):
self.cards.append(cardType)
self.setUp = True
def deal(self, player, amount):
if self.setUp:
for x in range(amount):
card = self.cards[0]
self.cards.remove(card)
player.cards.append(card)
else:
self.set_up()
self.deal(player, amount)
class Player():
cards = []
class Game():
def start(self):
stack = Stack()
players = [Player() for player in range(int(input("How many players?")))]
for player in players:
stack.deal(player, 1)
for player in players:
print(player.cards)
#all players have the same numbers of cards (the amount of players = number of cards)
#when all players should only have 1 card each since I put 1 in stack.deal
#it's also as if all players become one when I call that function.
我使用Game().start()
运行代码。
答案 0 :(得分:2)
对于从Java或C ++进入Python的人来说,这是一个常见的错误: 在类体上声明的属性实际上是 class 属性,并且对于该类的所有实例都是可见的同一对象。
要为每个类实例创建新的独立属性,必须将它们归入__init__
方法:
class Stack():
def __init__(self):
self.setup = False
self.cards = []
...
(另外,另一个" Javaism"在那里:并非所有代码都需要在Python中的方法内运行 - 所以,tehre在游戏类中使用start
方法是没有意义的像你一样使用它 - 如果它是一个单一的方法,只需取消" Game"类并将该代码移动到一个函数(def game(...):
)并调用它来开始)