10.6.2 Class Card—Introducing Class Attributes

Class Attributes FACES and SUITS

  • Each object of a class has its own copies of the class’s data attributes
  • A class attribute (also called a class variable) represents class-wide information
    • Belongs to the class, not to a specific object of that class
  • Two class attributes (lines 5–7):
    • FACES is a list of the card face names
    • SUITS is a list of the card suit names
# card.py
"""Card class that represents a playing card and its image file name."""

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

Class Attributes FACES and SUITS (cont.)

  • Define a class attribute by assigning a value to it inside the class’s definition, but not inside any of the class’s methods or properties (in which case, they’d be local variables)
  • FACES and SUITS are constants that are not meant to be modified
  • Style Guide for Python Code recommends naming your constants with all capital letters.

Class Attributes FACES and SUITS (cont.)

  • We’ll use FACES and SUITS to initialize each Card we create
  • Do not need a separate copy of each list in every Card object
  • Class attributes are typically accessed through the class’s name (as in, Card.FACES or Card.SUITS)
  • Class attributes exist as soon as you import their class’s definition

Card Method __init__

  • Method __init__ defines a Card’s _face and _suit data attributes
def __init__(self, face, suit):
        """Initialize a Card with a face and suit."""
        self._face = face
        self._suit = suit

Read-Only Properties face, suit and image_name

  • Once a Card is created, its face, suit and image_name do not change, so these are read-only properties
  • A property is not required to have a corresponding data attribute
  • Card property image_name’s value is created dynamically by getting the Card object’s string representation with str(self), replacing any spaces with underscores and appending the '.png' filename extension
@property
    def face(self):
        """Return the Card's self._face value."""
        return self._face

    @property
    def suit(self):
        """Return the Card's self._suit value."""
        return self._suit

    @property
    def image_name(self):
        """Return the Card's image file name."""
        return str(self).replace(' ', '_') + '.png'

Methods That Return String Representations of a Card

  • Card provides three special methods that return string representations
  • Method __repr__ returns a string representation that looks like a constructor expression
def __repr__(self):
        """Return string representation for repr()."""
        return f"Card(face='{self.face}', suit='{self.suit}')"

Methods That Return String Representations of a Card (cont.)

  • Method __str__ returns a string of the format 'face of suit'
def __str__(self):
        """Return string representation for str()."""
        return f'{self.face} of {self.suit}'

Methods That Return String Representations of a Card (cont.)

  • In the __str__ method of class DeckOfCards, we use f-strings to format the Cards in fields of 19 characters each
  • Class Card’s special method __format__ is called when a Card object is formatted as a string
def __format__(self, format):
        """Return formatted string representation for str()."""
        return f'{str(self):{format}}'
  • Second argument is the format string used to format the object
  • To use the format parameter’s value as a format specifier, enclose the parameter name in braces to the right of the colon

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.