我有一个如下的类:
class Hand():
def __init__(self, hand_a, play_deck, split_count, name): # hand_a for hand actual
self.hand_a = hand_a # the actual hand when instance created
self.play_deck = play_deck # need to move this to deck class
self.split_count = split_count
self.name = name在另一个类中,我创建了Hand的一个实例:
class DECK():
def __init__(self):
pass
def deal(self, play_deck):
dhand = {}
phand = {}
for i in range (2):
play_deck, phand[i] = pick_item(play_deck)
play_deck, dhand[i] = pick_item(play_deck)
# creat instance of Hand for player's starting hand
self.start_hand = Hand(phand, play_deck, 0, "Player 1")在第三个类中,我尝试访问我的第一个Hand实例,名为'start_hand':
class Game():
def __init__(self):
pass
def play_game(self):
self.deck = DECK()
self.deck.deal(play_deck)
print "dhand = %r" % start_hand.hand_a但我得到以下错误:
print "dhand = %r" % start_hand.hand_a
NameError: global name 'start_hand' is not defined我也尝试过:
print "dhand = %r" % self.start_hand.hand_a但我得到以下错误:
print "dhand = %r" % self.start_hand.hand_a
AttributeError: Game instance has no attribute 'start_hand'我是否必须以其他方式创建类实例,或者必须以不同方式访问它,或者两者都有?还是我太离谱了,我应该从头开始?
发布于 2012-08-23 21:45:23
您的对象是deck start_hand的成员。
print "dhand = %r" % self.deck.start_hand.hand_a发布于 2012-08-23 21:44:16
可以,您可以访问该属性。你想要的
self.deck.start_hand.hand_a
# ^ deck object you just created
# ^Hand object created by the deck constructor/initiator (DECK.__init__)
# ^ starting hand attribute of hand object.发布于 2012-08-23 21:44:05
你为什么不试试这个呢?
def deal(self, play_deck):
...
return start_hand否则,start_hand是DECK对象的成员,因此您必须:
self.deck.start_hand才能访问它。
https://stackoverflow.com/questions/12093000
复制相似问题