TDM 10200: Project 12 — Spring 2023
Objects and Classes in Python
A class can be considered a outline made by the user for creating objects. An easy way to think of it is class is a blueprint or sketch of a of a car, it contains all of the details we need to know, windows, doors, engine etc. Based on all the details and descriptions we build the vehicle. The car itself is the object. Since we can have many cars created using the same description and details the idea is that we can create many objects from a class. An object is an instance
of the class with actual values. An object is an (actual) specific car. A red compact car with black interior and tinted windows. You can now create multiple instances, using the blueprint of a class as a guide, to help you know what information is required.
Objects consist of:
-
State: attributes/properties of an object
-
Behavior: the methods of the object and also its response to other objects
-
Identity: gives a unique name to the object and that allows for interaction between objects.
Identity |
State/Attributes |
Behavior |
Miata |
Mazda, Red, 2019 |
acceleration, steering, braking |
Instantiating a Class == Declaring Objects All instances share the same attributes and the same behavior but the values of the attributes(State) are unique.
Insider Knowledge
ONE
Let’s start simple and declare an object
class CAR:
#attibute
attr1 = "red"
attr2 = "fast"
#sample method
#self refers to the class of which the method belongs
def fun(self):
print("The car is", self.attr1)
print("The car is", self.attr2)
#object instantiaton
Miata = CAR()
-
What happens when you type:
print(Miata)
-
What happens when you type:
Miata.fun()
-
Now create and declare your own object. We encourage you to make a class of your own and try it out, e.g., make a class for a
BOOK
or aKITCHEN
or aUNIVERSITY
or aDOG
.
You might want to also experiment further with the Miata, e.g., you might want to try: Miata.attr1
and Miata.attr2
and add some attributes. It is worthwhile to play a little bit with the CAR
!
-
Answers to the questions a,b,c above.
-
Code used to solve this problem.
-
Output from running the code.
TWO
Lets play with cards!
The code below defines two different types of classes:
class Card:
#mapping each possible card number(2-10,J,Q,K,A) to a numerical value
_value_dict = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8":8, "9":9, "10": 10, "j": 11, "q": 12, "k": 13, "a": 14}
def __init__(self, number, suit):
if str(number).lower() not in [str(num) for num in range(2, 11)] + list("jqka"):
raise Exception("Number wasn't 2-10 or J, Q, K, or A.")
else:
self.number = str(number).lower()
if suit.lower() not in ["clubs", "hearts", "diamonds", "spades"]:
raise Exception("Suit wasn't one of: clubs, hearts, spades, or diamonds.")
else:
self.suit = suit.lower()
def __str__(self):
return(f'{self.number} of {self.suit.lower()}')
def __repr__(self):
return(f'Card(str({self.number}), "{self.suit}")')
def __eq__(self, other):
if self.number == other.number:
return True
else:
return False
def __lt__(self, other):
if self._value_dict[self.number] < self._value_dict[other.number]:
return True
else:
return False
def __gt__(self, other):
if self._value_dict[self.number] > self._value_dict[other.number]:
return True
else:
return False
def __hash__(self):
return hash(self.number)
class Deck:
brand = "Bicycle"
_suits = ["clubs", "hearts", "diamonds", "spades"]
_numbers = [str(num) for num in range(2, 11)] + list("jqka")
def __init__(self):
self.cards = [Card(number, suit) for suit in self._suits for number in self._numbers]
def __len__(self):
return len(self.cards)
def __getitem__(self, key):
return self.cards[key]
def __setitem__(self, key, value):
self.cards[key] = value
-
Create an instance of the class Card and call it
my_card
. Then run:print(my_card)
and also run:my_card
-
What is the difference in the output?
-
Create an instance of the class Deck and call it
my_deck
. Now what is the number of items you will find in the objectmy_deck
Helpful Hint (for c)
len(my_deck)
It is important to point out that a Python function inside a class
is called a method.
We can initialize values using constructors there is an
__int__()
function that is called whenever a new object of that class is instantiated.
THREE
Modify the Class Deck to return a string that says "a bicycle deck with 52 cards".
-
Code used to solve this problem.
-
Output from running the code.
FOUR
Let’s create a new class called Player
We will use this to represent a player in a game.
The following features must be included:
-
A
deck
to draw from -
A
hand
of cards -
The
name
of the player -
A
draw
method that draws a card from the deck and adds it to the hand.
Helpful Hint
Knowing that each person will have a different name, the name
attribute will be an instance attribute. The name
argument will be used to assign a name to a player, and the deck
argument is used to assign the deck to the player. The hand of cards should be an empty list at initialization. The draw method will be used to draw a card from the deck and add it to a player’s hand.
-
Answers to the question above
-
Code used to solve this problem
-
Output from running the code.
FIVE
What card does Liz draw? Create a Deck
and a Player
, and draw a card from the deck. Print the value on the card that is drawn.
Helpful Hint
my_deck1 = Deck()
player1 = Player("Liz", my_deck1)
card = player1.draw()
print(card)
-
The answer to the question above.
-
Code used to solve this problem.
-
Output from running the code.
Please make sure to double check that your submission is complete, and contains all of your code and output before submitting. If you are on a spotty internet connection, it is recommended to download your submission after submitting it to make sure what you think you submitted, was what you actually submitted. In addition, please review our submission guidelines before submitting your project. |