Pets Own the Owners
Given these two classes, what do the following lines evaluate to?
class Owner(object):
all = []
def __init__(self, name):
self.name = name
self.pets = []
Owner.all.append(self)
def add_pet(self, pet):
self.pets.append(pet)
def __repr__(self):
return 'Owner(' + self.name + ')'
class Pet(object):
all = []
def __init__(self, name, weight, height):
self.name = name
self.weight = weight
self.height = height
Pet.all.append(self)
@property
def bmi(self):
return self.weight / (self.height * self.height)
def __repr__(self):
return 'Pet(' + self.name + ')'
>>> bob = Owner('bob')
>>> joe = Owner('joe')
>>> bob.all #1
>>> bob.all.append(bob)
>>> joe.all #2
>>> type(joe.add_pet) #3
>>> type(Owner.add_pet) #4
>>> harry = Pet('harry', 50, 50)
>>> type(harry.bmi) #5
>>> joe.pets.append(harry)
>>> bob.add_pet(harry)
>>> bob.pets[0].all #6
>>> bob.pets.append(Pet('jimmy', 40, 10))
>>> bob.pets[1].owner #7
>>> Pet.all #8
>>> jimmy #9
- [Owner(bob), Owner(joe)]
- [Owner(bob), Owner(joe), Owner(bob)]
- <class ‘method’>
- <class ‘function’>
- <class ‘float’>
- [Pet(harry)]
- Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
AttributeError: ‘Pet’ object has no attribute ‘owner’ - [Pet(harry), Pet(jimmy)]
- Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘jimmy’ is not defined
I don't claim to be perfect so if you find an error on this page, please send me an email preferably with a link to this page so that I know what I need to fix!