Practice: Instance Variables

« Read the chapter

Q1. Store three variables

BeginnerCoding

Write class `Movie` with constructor storing `title`, `year` and `rating`. Print them for Movie("Up", 2009, 8).

Goal: Create instance variables.

Q2. Independent objects

BeginnerCoding

Create two `Student` objects with names Ana and Raj. Change Ana's name to Anu and print both names.

Goal: Instance variables are separate.

Q3. Show vars

IntermediateCoding

Create class `Pt` with x and y. Print `vars` of Pt(1, 2).

Goal: Inspect objects.

Q4. Use getattr with default

IntermediateCoding

Create an empty class object `o`. Print `getattr(o, "colour", "unknown")`.

Goal: Use getattr.

Q5. setattr and hasattr

IntermediateCoding

Using setattr, add attribute `speed` = 40 to a `Car` object, then print `hasattr(car, "speed")` and the value.

Goal: Use setattr and hasattr.

Q6. Remember between calls

IntermediateCoding

Write class `Meter` with `km` starting at 0 and method `drive(d)` adding d. Drive 10 then 15 and print km.

Goal: Persistent state.

Q7. Own copy of a list

AdvancedCoding

Write class `Notes` that stores a copy of the list passed to it. Pass `[1]`, append 2 to the object's list and print the original list.

Goal: Avoid shared lists.

Q8. Delete an attribute

AdvancedCoding

Create an object with attribute `tmp`, delete it with `del`, and print whether it still exists using hasattr.

Goal: Delete attributes.

Q9. Two objects

BeginnerOutput

What does this print?

Code
class A:
    def __init__(self, v):
        self.v = v

x = A(1)
y = A(2)
x.v += 10
print(x.v, y.v)

Goal: Separate values.

Q10. Local trap

IntermediateOutput

What does this print?

Code
class B:
    def __init__(self):
        self.n = 0

    def inc(self):
        n = self.n + 1

b = B()
b.inc()
b.inc()
print(b.n)

Goal: Local vs instance.

Q11. Dict view

IntermediateOutput

What does this print?

Code
class C:
    def __init__(self):
        self.a = 1
        self.b = 2

c = C()
c.c = 3
print(sorted(vars(c)))

Goal: Inspect objects.

Q12. Shared list

AdvancedOutput

What does this print?

Code
class D:
    def __init__(self, data):
        self.data = data

lst = [1, 2]
d = D(lst)
d.data.append(3)
print(lst)

Goal: Mutable sharing.

Q13. hasattr

BeginnerOutput

What does this print?

Code
class E:
    def __init__(self):
        self.x = 1

e = E()
print(hasattr(e, "x"), hasattr(e, "y"))

Goal: Use hasattr.

Q14. Method creates variable

AdvancedOutput

What does this print?

Code
class F:
    def setup(self):
        self.ready = True

f = F()
print(hasattr(f, "ready"))
f.setup()
print(hasattr(f, "ready"))

Goal: When variables get created.

Q15. Fix the missing self

BeginnerDebugging

This prints an error. Fix it. Expected output: 12

Code
class R:
    def __init__(self, w, h):
        w = w
        h = h

    def area(self):
        return self.w * self.h

print(R(3, 4).area())

Goal: Save values on the object.

Q16. Fix the counter

IntermediateDebugging

The count always prints 0. Fix it. Expected output: 2

Code
class Cn:
    def __init__(self):
        self.count = 0

    def add(self):
        count = self.count + 1

c = Cn()
c.add()
c.add()
print(c.count)

Goal: Update instance variables.

Q17. Fix the shared list

AdvancedDebugging

Both bags show the same items. Fix it so the output is: [] then ['a']

Code
class Bag:
    def __init__(self, items=[]):
        self.items = items

b1 = Bag()
b2 = Bag()
b2.items.append("a")
print(b1.items)
print(b2.items)

Goal: Avoid mutable defaults.

Q18. Instance vs local

BeginnerConceptual

Explain the difference between `self.total` and `total` inside a method.

Goal: Compare variable kinds.

Q19. Design a Product

IntermediateApplication

List the instance variables a `Product` class in an online shop should have and why.

Goal: Plan object data.