S3 print generic仅在显式调用print时调用S4 print方法

时间:2016-10-06 01:51:53

标签: r oop s4

我正在尝试为R S4对象创建一个print方法,以便在控制台上键入对象的名称时调用print方法。我可以构造它,以便在我显式调用print()时调用正确的方法,但是当我只是将对象键入屏幕时则不会。我们欢迎所有的建议!

setClass("Person",
     slots = list(name = "character", age = "numeric"))

alice <- new("Person", name = "Alice", age = 40)
print.Person <- function(x,...) print("This is a person object")
setMethod("print","Person",print.Person)

# Behavior that I want
print(alice)
[1] "This is a person object"

# Not the behavior that I want
alice
An object of class "Person"
Slot "name":
[1] "Alice"

Slot "age":
[1] 40

1 个答案:

答案 0 :(得分:3)

我不是S4的优秀专家,但我不认为你应该将S3的特工与S4混合使用。正如show文档中所指出的,您可以为您的目的定义该方法,

setClass("Person", slots = list(name = "character", age = "numeric"))

alice <- new("Person", name = "Alice", age = 40)

setMethod("show", "Person",
          function(object) print(paste("This is a person object named", 
                                       object@name))
         )

alice
# [1] "This is a person object named Alice"
print(alice)
# [1] "This is a person object named Alice"

这是您正在寻找的行为。