MulaiMulai sekarang secara gratis

Writing the Next Method

When objects have multiple classes, you may wish to call methods for several of these classes. This is done using NextMethod() (docs).

The S3 methods now take the form:

an_s3_method.some_class <- function(x, ...)
{
  # Act on some_class, then
  NextMethod("an_s3_method")
}

That is, NextMethod() should be the last line of the method.

Latihan ini adalah bagian dari kursus

Object-Oriented Programming with S3 and R6 in R

Lihat Kursus

Petunjuk latihan

The variable kitty, and the generic what_am_i() function have been predefined in your workspace.

  • Inspect your workspace with ls.str().
  • Complete the definition of the cat method for what_am_i().
    • Write a message() (docs) stating "I'm a cat".
    • Call NextMethod() (docs), passing the name of the generic as a string.
  • Define a mammal method for what_am_i().
    • The arguments are the same as for the cat method.
    • Write a message() stating "I'm a mammal".
    • Call NextMethod().
  • Define a character method for what_am_i().
    • The arguments are the same as for the cat method.
    • Write a message() stating "I'm a character vector".
    • Don't call NextMethod().
  • Call what_am_i() with kitty as an input, verifying that all three messages are shown.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# Inspect your workspace
ls.str()

# cat method
what_am_i.cat <- function(x, ...)
{
  # Write a message
  ___
  # Call NextMethod
  ___
}

# mammal method
___ <- ___

# character method
___ <- ___

# Call what_am_i()
___
Edit dan Jalankan Kode