Getting the name of the class being used in a S3 method call

Is there a way to get the actual class name being used when calling a S3 method?

For example, is there a way to have foo.bar() always print Call method for class: bar independently of the order (and without knowing other class names) of the classes defined in structure()?

foo <- function(x) {
  UseMethod("foo")
}

foo.bar <- function(x) {
  cat("Call method for class:", class(x)[[2]])
}

x <- structure("x", class = c("baz", "bar", "character"))
foo(x)

perhaps your example abstracts away more than you intend; but my first instinct is to say, foo.bar can know that it is itself, so why interrogate x ?

foo.bar <- function(x) {
  cat("Call method for class is foo.bar, because thats the function
  this comment was written in")
}
1 Like

A more concrete example (and closer to what I'm trying to achieve) could be to create a str method from a template body that I can reuse:

library(vctrs)

str_body <- function(x, cls) {
  cat(sprintf(" %s <%s elements>\n", cls, length(x)))
}

obj_str_data.bar <- function(x, ...) {
  str_body(x, function_that_returns_current_class(x))
}

str.bar <- function(object, ...) {
  obj_str(object, ...)
}

list(y = 1:3, z = foo(x)) |> str()

In my case, I've an object that gets new classes in the building process. This is not something I usually do but it makes sense in my case I guess. I can easily get around my issue by changing my design a bit or by appending (instead of prepending) the new classes so that the first class of my object is the one I want to display.

The initial question is motivated by curiosity.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.