RConsortium / S7

S7: a new OO system for R
https://rconsortium.github.io/S7
Other
387 stars 33 forks source link

Should the default print method from a class respect a property's already defined print method? #350

Closed calderonsamuel closed 1 year ago

calderonsamuel commented 1 year ago

This is just a toy example.

Here I define a custom_property class and its print method. It behaves as expected.

library(S7)
#> Warning: package 'S7' was built under R version 4.3.1

custom_property <- new_class(
    name = "custom_property",
    properties = list(
        a = class_numeric,
        b = class_numeric
    )
)

method(print, custom_property) <- function(x) {
    cat("Hello custom property")
}

custom_property()
#> Hello custom property

However, if I use the class as a property of a new class, another print method is used.

foo <- new_class(
    name = "foo",
    properties = list(
        bar = custom_property
    )
)

foo()
#> <foo>
#>  @ bar: <custom_property>
#>  .. @ a: int(0) 
#>  .. @ b: int(0)

If I access the property it behaves as expected.

foo()@bar
#> Hello custom property

Is there a way to make the print method from the foo class "respect" the print method of the custom_property class? Should I just define a print method for foo?


sessioninfo::session_info(pkgs = "attached")
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.3.0 (2023-04-21 ucrt)
#>  os       Windows 11 x64 (build 22621)
#>  system   x86_64, mingw32
#>  ui       RTerm
#>  language (EN)
#>  collate  Spanish_Peru.utf8
#>  ctype    Spanish_Peru.utf8
#>  tz       America/Lima
#>  date     2023-09-12
#>  pandoc   3.1.1 @ C:/Program Files/RStudio/resources/app/bin/quarto/bin/tools/ (via rmarkdown)
#> 
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  package * version date (UTC) lib source
#>  S7      * 0.1.0   2023-08-24 [1] CRAN (R 4.3.1)
#> 
#>  [1] C:/Users/dgco93/AppData/Local/R/win-library/4.3
#>  [2] C:/Program Files/R/R-4.3.0/library
#> 
#> ──────────────────────────────────────────────────────────────────────────────

Created on 2023-09-12 with reprex v2.0.2

hadley commented 1 year ago

The default print() method calls str() in order to generate a compact representation suitable for display in a bulleted list. So if you wanted to customise this display, you could also provide a method for str(). str() methods are a little trickier than print methods, but you can see the most important ideas in the str.S7_object() implementation: