Python:我可以从类bar中创建的类foo访问类实例吗?

时间:2012-08-23 13:41:50

标签: python class instance

我有一个课程如下:

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")

在第三节课中,我试图访问我的第一个名为'start_hand'的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'

我是否必须以其他方式创建类实例,或者我是否必须以不同方式或两者同时访问它?或者我是这样离开的,我应该重新开始?

4 个答案:

答案 0 :(得分:4)

是的,您可以访问该属性。你想要

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.

答案 1 :(得分:1)

你为什么不尝试这个?

def deal(self, play_deck):
  ...
  return start_hand

否则start_handDECK对象的成员,因此您必须:

self.deck.start_hand

访问它。

答案 2 :(得分:1)

您的start_handdeck对象的成员。

print "dhand = %r" % self.deck.start_hand.hand_a

答案 3 :(得分:0)

  

我是否必须以其他方式创建类实例,或者我是否必须以不同方式或两者同时访问它?或者我是这样离开的,我应该重新开始?

你的问题是OO设计之一,而不是python特有的功能。确定您希望GameDECKHand如何相互关联。通常,适当的解决方案是在封闭类中创建一个将委托给其成员的方法。

很难提出具体的建议,因为看起来这可能是一些调试代码。但也许你可以替换

print "dhand = %r" % start_hand.hand_a

print str(self.deck)

只要您向__str__添加Deck方法:

def __str__(self):
    return str(self.start_hand)

为了有用,您可能还需要一个Hand课程。

未经请求的建议:hand_a的{​​{1}}(“手实际”)成员创造了一个相当令人困惑的比喻。考虑将其作为Hand的属性或其他可能更有意义的属性。