filmov
tv
R Tutorial: Object-Oriented Programming in R: S3 & R6 (part 4)

Показать описание
Learn how to inherit from an R6 class, and how the relationship between parent and child classes works.
On my far right is the microwave that you saw in the previous chapter. Next to it is a new fancy microwave with extra features. Recall that the original microwave has four pieces of functionality. You can open and close the door, set the power level, and cook some food.
The fancy microwave has all of the functionality of the original microwave, but it also has a "popcorn" button.
If you want to define an R6 class for the fancy microwave, you could just copy and paste the definition from the original microwave, and then start adding new features. Unfortunately, copying and pasting is a really big source of bugs, and is usually a sign that you are writing bad code. If you change the definition of the original microwave, you really want a way for those changes to automatically be mirrored in the fancy microwave.
R6 achieves this through the concept of inheritance. Let's take a look at how it works. Here's the pattern for an R6 class.
To create a class that inherits from this class, you use the inherit argument. The classes that inherit from the original are called child classes. The original class is called the parent of the child classes. Here you see a Child Thing that inherits from the Thing class.
All of the data and functionality of the parent class is passed on to the child. That is, all the fields from the private, public, and active elements. So without defining anything extra, the Child Thing already has two private data fields and a method.
You can add any additional functionality that you like to the child.
Now the child class has everything that the parent has, and an extra method. The important thing to remember is that inheritance only works in one direction. If you are a parent, this will probably sound familiar. Children take everything from their parent, but the parent doesn't get anything back.
When you talk about the relationship between the microwaves, you can say that a fancy microwave is a microwave, but the converse doesn't hold. It wouldn't be true to say that any microwave is a fancy microwave.
This translates into how classes are ascribed to R6 objects. The class of a thing is a character vector of "Thing" and "R6". That is, the thing object inherits from "Thing" and it inherits from "R6".
The class of the child thing also includes "ChildThing".
To summarize, you can propagate functionality from one class to another using inheritance. This is achieved by using the inherit argument of R6Class. The child class gets all the data fields and functions from the parent class, but the converse is not true. That is, the parent class does not inherit the traits of its child.