13.1 Inheritance basics
2.
b.
A kitchen has a freezer, so a
Kitchen
class would contain a Freezer
instance. A has-a relationship is also called a composition.
5.
a.
Deriving
CarryOn
from Luggage
is specified in CarryOn'
s class definition. Ex:
class CarryOn(Luggage):
. Instances of a subclass, like CarryOn
, are created like other classes and do not require the base class name.
6.
c.
A
SubClass
instance has access to func_1()
, inherited from SuperClass
, as well as to func_2()
, a SubClass
method.
7.
a.
A
SuperClass
instance has access to SuperClass'
s func_1()
but doesn't have access to anything in SubClass
, including func_2()
.
13.2 Attribute access
1.
b.
dev_1
is the second Employee
created. So dev_1
is the second object to call Employee
.__init__()
, and dev_1.e_id
is assigned with
2
.
5.
c.
dev_display()
is a Developer
method. emp_1
is not a Developer
instance, so emp_1
cannot access dev_display()
.
6.
a.
Instance attributes inherited from
Employee
, the superclass, are accessed the same way as the subclass Developer'
s instance attributes.
13.3 Methods
1.
b.
Overriding involves defining a subclass method that has the same name as the superclass method.
3.
c.
The class definition doesn't indicate inheritance. The definition should be
class ContractTax(Tax):
.
5.
a.
super()
.__init__(4)
calls the __init__()
of Rectangle'
s superclass, Polygon
. Control moves to line 3, and num_sides
is initialized with 4
.
13.4 Hierarchical inheritance
2.
b.
Employee would be an appropriate superclass for
Developer
and SalesRep
. Developer
and SalesRep
are not directly related.
4.
b.
c_inst
has access to C'
s instance attribute, c_attr
, as well the inherited attribute from A
, a_attr
.
5.
b.
D
, which inherits from B
, so d_inst
inherits b_attr
. B
also inherits from A
, so d_inst
inherits d_attr
.
13.5 Multiple inheritance and mixin classes
2.
b.
An argument is not passed to
C'
s __init__()
for c_attr
, so c_attr
is assigned with the default value,
20
.
5.
b.
eat()
can be moved into a mixin class included in Pitcher'
s and VenusFlyTrap'
s inheritance list.
6.
b.
Good practice is to have a mixin class name end in
"Mixin"
to identify the class's purpose. The final implementation is:
class Plant:
def photosynth(self):
print("Photosynthesizing")
class CarnivMixin:
def eat(self):
print("Eating")
class Rose(Plant):
pass
class Pitcher(Plant, CarnivMixin):
pass
class VenusFlyTrap(Plant, CarnivMixin)
pass