Tip When not to use inheritance

In some cases, writing a subclass that inherits from a superclass isn't the best solution. Suppose you are planning a conference, and you created a Registration class. You might think of making Registration inherit from NameTag so you can

TECHNICAL STUFF

Classes that subclasses inherit from are called parent classes, superclasses, or base classes.

use the say() method. But it's better to make a nametag attribute for the registration class that uses NameTag as a value, like this:

class Registration:

def init (self, name): self.name = name self.nametag = NameTag(name)

Using an attribute that refers to an instance of a different class is called object composition. One way to describe what's going on in the above example is to say that an instance of the Registration class has an attribute that is an instance of the NameTag class. To put it in material-world terms, if you produce a bunch of registration packets for a conference, each packet is like an instance of the Registration class, and each package has a name tag in it, which is an instance of the NameTag class.

Here's what happens when you create an instance of the class and the subclass and call each instance's say() method:

Hello, my name is Lucy

The current value of my name is Linus

Was this article helpful?

0 0

Post a comment