2015-10-22 89 views
-3

我正在处理一个程序,但我得到的错误“类型对象'卡'没有属性fileName。我已经找到这个答案,但没有我见过的类似的情况下,这个类型对象没有属性

class Card: 
RANKS = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) 
SUITS = ('s', 'c','d','h') 
BACK_Name = "DECK/b.gif" 

def __init__(self, rank, suit): 
    """Creates a card with the given rank and suit.""" 
    self.rank = rank 
    self.suit = suit 
    self.face = 'down' 
    self._fileName = 'DECK/' + str(rank) + suit[0] + '.gif' 

class TheGame(Frame): 

    def __init__(self): 
     Frame.__init__(self) 
     self.master.title("Memory Matching Game") 
     self.grid() 

     self.BackImage = PhotoImage(file = Card.BACK_Name) 
     self.cardImage = PhotoImage(file = Card.fileName) 

解决这个任何帮助将是巨大的感谢

+0

你期望'Card.fileName'做什么,为什么? – user2357112

+0

我有其他代码会随机创建一个字符串在别处选取一张牌,然后我在TheGame中调用它,以便我可以将随机图像分配给imageLabel。 – BradRisch

+1

是的,但是这与'Card.fileName'有什么关系?你认为这个属性来自哪里? – user2357112

回答

2

你有三个属性:。。。RANKSSUITSBACK_Name

class Card: 
    # Class Attributes: 
    RANKS = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) 
    SUITS = ('s', 'c','d','h') 
    BACK_Name = "DECK/b.gif" 

您尚未将fileName定义为类属性,因此试图获取名为fileName的属性将引发一个AttributeError,指示它不存在。

这是因为fileName,或者更确切地说,_fileName已经通过self._filename属性定义为实例:

# Instance Attributes: 
def __init__(self, rank, suit): 
    """Creates a card with the given rank and suit.""" 
    self.rank = rank 
    self.suit = suit 
    self.face = 'down' 
    self._fileName = 'DECK/' + str(rank) + suit[0] + '.gif' 

要访问此属性,您必须先创建一个实例c = Card(rank_value, suit_value)对象Card;那么您可以通过c._filename访问_filename

+0

谢谢!这有很大帮助。 – BradRisch

相关问题