Define an object of S3 class "bar" and a print method:
foo=list(1)
class(foo) <- c("bar")
print.bar <- function(x,...){
cat("print.bar says this was ",deparse(substitute(x)),"\n")
}
Now print(foo) does this:
> print(foo)
print.bar says this was foo
Great, but auto-printing fails:
> foo
print.bar says this was structure(list(1), class = "bar")
I'm guessing this is something to do with the way the line is evaluated as a top-level expression. Had a quick search on R-devel to no avail. Anyone know how to fix it?
The reason I want the name is because the thing I am defining is a function, and I want to be able to put 'try foo(2)' in the print method (getting 'foo' from the name of the object). Yes, you can subclass functions in S3. I suppose there may be other pifalls..
This is a rather special case, as R substitutes
foo
by its value before callingprint
when you type the name at the command line. This can be illustrated by :ergo, without the name as an attribute (like Aaron showed), there is no way on earth you'll extract the name of the object from anywhere. It's simply not there in the callstack.