首页 > 解决方案 > 我很困惑,类 Card 对象不能手动设置但通过不同的类成功设置

问题描述

这是班级卡代码

class Card:
"class time definetion"
SUITS = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
FACES = ['Hearts', 'Diamonds', 'Clubs', 'Spades']

def __init__(self, face, suit):
    self.face = face
    self.suit = suit

@property
def face(self):
    return self._face

@property
def suit(self):
    return self._suit

@property
def image_name(self):
    return str(self.suit).replace(' ', '_') + '.png'

def __repr__(self):
    return f'Card(face="{self.face}", suit="{self.suit}")'

def __str__(self):
    return f'{self.face} of {self.suit}'
def __format__(self, format):
    return f'{str(self):{format}}'

但是当我试图创建一个类的对象时

w = Card(Card.FACES[1], Card.SUITS[1])

这是我得到的错误

AttributeError Traceback(最近一次调用最后一次)

----> 1 w = Card(Card.FACES[1], Card.SUITS[1])

in init(自我,脸,西装)

  5 

  6     def __init__(self, face, suit):

----> 7 self.face = 脸

  8         self.suit = suit

  9 

AttributeError:无法设置属性

然后我就好了,因为我只定义了getter而不是setter,但是为什么通过下面的类成功创建了对象而没有错误,因为该类还创建了Card对象这是第二个类代码

import random
from card import Card #to import the previous class
class DeckOfCards:
     NUMBER_OF_CARDS = 52 # constant number of Cards
      def __init__(self):
    """Initialize the deck."""
          self._current_card = 0
          self._deck = []

          for count in range(DeckOfCards.NUMBER_OF_CARDS):
              self._deck.append(Card(Card.FACES[count % 13],
               Card.SUITS[count // 13]))

*如您所见,第二个类也生成 Card 对象,但我很困惑,如果没有前面的错误,这怎么可能???*

标签: python

解决方案


你把你的属性名弄乱了一点,在你的__init__, 你有self.faceself.suit作为属性,在你的类中,你还定义了具有相同名称和使用属性的 getter,并且self._faceself._suit你的 init 中没有定义。您可以通过将 init 更改为:


def __init__(self, face, suit):
    self._face = face
    self._suit = suit

可能您的其他方法也受到影响,我相信您可以自己修复它们。


推荐阅读