Getting the object name for S3 print method failing

蹲街弑〆低调 提交于 2019-12-04 17:02:36

问题


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..


回答1:


This is a rather special case, as R substitutes foo by its value before calling print when you type the name at the command line. This can be illustrated by :

foo=list(1)
class(foo) <- c("bar")
print.bar <- function(x,...){
  print(sys.calls())
}

> foo
[[1]]
print(list(1))

[[2]]
print.bar(list(1))

> print(foo)
[[1]]
print(foo)

[[2]]
print.bar(foo)

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.




回答2:


If you're not going to be renaming the object, you could include the name as an attribute and print that instead.

foo <- structure(list(1), class="bar", name="foo")
print.bar <- function(x,...){
  cat("print.bar says this was",attr(x, "name"),"\n")
}

Then it does what you expect:

> print(foo)
print.bar says this was foo 
> foo
print.bar says this was foo 

Unless you use a different name for the same object:

> fooX <- foo
> fooX
print.bar says this was foo 


来源:https://stackoverflow.com/questions/4959463/getting-the-object-name-for-s3-print-method-failing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!