Class Attributes
Class Attributes are values specified in a class that are shared by all instances of that class! We can access class attributes from any instance of that class, but changing those values anywhere changes them for every instance.
class A:
dirs = ["up", "down", "left", "right"]
# typically access class attributes directly via the class (no instance!)
print(A.dirs) # ['up', 'down', 'left', 'right']
# can also access via an instance:
a = A()
print(a.dirs)
# but there is only one shared value across all instances:
a1 = A()
a1.dirs.pop() # not a good idea
a2 = A()
print(a2.dirs) # ['up', 'down', 'left'] ('right' is gone from A.dirs)
Playing Card Demo
# oopy-playing-cards-demo.py
# Demos class attributes, static methods, repr, eq, hash
import random
class PlayingCard:
numberNames = [None, "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"]
suitNames = ["Clubs", "Diamonds", "Hearts", "Spades"]
CLUBS = 0
DIAMONDS = 1
HEARTS = 2
SPADES = 3
@staticmethod
def getDeck(shuffled=True):
deck = [ ]
for number in range(1, 14):
for suit in range(4):
deck.append(PlayingCard(number, suit))
if (shuffled):
random.shuffle(deck)
return deck
def __init__(self, number, suit):
# number is 1 for Ace, 2...10,
# 11 for Jack, 12 for Queen, 13 for King
# suit is 0 for Clubs, 1 for Diamonds,
# 2 for Hearts, 3 for Spades
self.number = number
self.suit = suit
def __repr__(self):
number = PlayingCard.numberNames[self.number]
suit = PlayingCard.suitNames[self.suit]
return f'<{number} of {suit}>'
def getHashables(self):
return (self.number, self.suit) # return a tuple of hashables
def __hash__(self):
# you are not responsible for this method
return hash(self.getHashables())
def __eq__(self, other):
return (isinstance(other, PlayingCard) and
(self.number == other.number) and
(self.suit == other.suit))
# Show this code in action
print("Demo of PlayingCard will keep creating new decks, and")
print("drawing the first card, until we see the same card twice.")
print()
cardsSeen = set()
diamondsCount = 0
# Now keep drawing cards until we get a duplicate
while True:
deck = PlayingCard.getDeck()
drawnCard = deck[0]
if (drawnCard.suit == PlayingCard.DIAMONDS):
diamondsCount += 1
print(" drawnCard:", drawnCard)
if (drawnCard in cardsSeen): break
cardsSeen.add(drawnCard)
# And then report how many cards we drew
print("Total cards drawn:", 1+len(cardsSeen))
print("Total diamonds drawn:", diamondsCount)