OOP Flashcards
(21 cards)
What is a class in Python?
A class is a blueprint for creating objects. It defines attributes (data) and methods (functions) that the objects created from it will have.
What is the purpose of the __init__ method in a class?
__init__ is a special method that gets called automatically when a new object is created. It initializes the object’s attributes.
What is an attribute?
An attribute is a variable that belongs to an object (e.g., self.name, self.energy).
What is a method?
A method is a function that belongs to a class and can operate on objects of that class (e.g., move(), eat()).
How do you create an instance of a class?
By calling the class like a function: my_pet = Pet(“jimmy”).
How do you access an object’s attributes from outside the class using dot notation?
my_pet.name or my_pet.energy.
How do you call an object’s methods from outside the class using dot notation?
my_pet.move() or my_pet.sleep(2).
How do you access an object’s attributes from inside the class using dot notation?
Use self.attribute_name, like self.energy.
How do you call an object’s methods from inside the class using dot notation?
Use self.method_name(), like self.die().
What attributes does a Pet have?
name, x, y, energy, hunger, alive, direction
What are the default values for each attribute?
x = 0, y = 0, energy = 5, hunger = 5, alive = True, direction = 0
What are two ways to create a Pet?
pet1 = Pet(“jimmy”)
# Default location (0,0)
pet2 = Pet(“someone”, 5, 7)
# Custom location (5,7)
How are pet directions represented internally?
0 = up, 1 = right, 2 = down, 3 = left
How do the turn methods ensure that direction stays valid?
urn_right resets direction to 0 if it becomes 4.
turn_left resets direction to 3 if it becomes -1.
How far does a Pet move each time move() is called?
One unit in the direction it is facing.
How is the direction of movement determined in move()?
By checking the direction attribute and updating x or y accordingly.
Which methods modify the Pet’s energy?
sleep() (increases)
play() (decreases)
Which methods modify the Pet’s hunger?
eat() (decreases)
play() (increases)
What is the range of possible values for energy and hunger?
energy: 0 to 10 (capped in sleep())
hunger: no explicit max/min, but implied 0 minimum in eat()
How/where are guard clauses used to prevent invalid states?
In eat(), sleep(), play(), and kill(): checks if self.alive or other.alive is False.
In kill(), what do self and other mean?
self: the Pet doing the attacking
other: the Pet being attacked