class TransitCard:
"""A reloadable transit fare card. Money is stored in whole cents."""
FARE = 330 # class attribute: one value shared by every card
def __init__(self, owner, balance=0):
"""Create a card for owner with a starting balance in cents."""
self.owner = owner # instance attributes:
self.balance = balance # each card object has its own
self.rides = 0
def load(self, cents):
"""Add money (in cents) to the card."""
self.balance += cents
def tap(self):
"""Pay one fare if possible. Return True if the rider may board."""
if self.balance >= TransitCard.FARE:
self.balance -= TransitCard.FARE
self.rides += 1
return True
return False
@classmethod
def from_text(cls, line):
"""Alternative constructor: build a card from "owner,cents" text."""
owner, cents = line.split(",")
return cls(owner.strip(), int(cents))
def __str__(self):
"""Return a readable description, used by print() and str()."""
return f"{self.owner}: ${self.balance / 100:.2f}, rides: {self.rides}"
ana = TransitCard("Ana", 500)
ben = TransitCard("Ben")
print(ana.tap(), ana.tap())
ben.load(1000)
print(ben.tap())
print(ana)
print(ben)
print(vars(ben))
transit.py with a short demo at the bottom.