What is left of the bundle a class was supposed to guarantee once outside code can assign `a.age = "twelve"` or bolt a brand-new attribute onto one instance?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The given Critter class defines exactly two data attributes, and one critter aged 4 has already been built. From outside the class, make all three of the moves this video warns about on critter:
name attribute to the string "furball",age attribute with the string "twelve",size holding the string "tiny".Every one of those lines runs without a complaint — that silence is the exercise.
class Critter(object):
""" A critter with a name and an age """
def __init__(self, age):
""" age is an int """
self.name = None
self.age = age
critter = Critter(4)Three moves Python allows but you should not make
List reading a.age from outside, assigning a.age = "twelve" where later methods assume a number, and bolting a.size = "tiny" onto one instance, and note all three are fine inside the class definition.
animal_dict(L) over L = [2,5,'a',-5,0]
Write the function that keeps the elements passing type(n) == int and n >= 0 and adds d[n] = Animal(n), and record that dictionaries take straight indexing, with no append and no plus.
Printing a container of objects
Record that print(animals) shows <__main__.Animal object at 0x...> for every value and that print runs only at the top level, then write the animals.items() loop printing animal:None:2, animal:None:5 and animal:None:0.