r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
404 stars 56 forks source link

Assign methods/variables from inherited class as private? #138

Closed sckott closed 5 years ago

sckott commented 6 years ago

If I have an R6 class like

A <- R6::R6Class(
  classname = 'A',
  public = list(
    foo1 = function(x) x,
    foo2 = function(x) x,
    foo3 = function(x) x,
    foo4 = function(x) x
  )
)

Then another class that inherits A like

B <- R6::R6Class(
  classname = 'B',
  inherit = A,
  public = list(hello = function(x) x),
  private = list(world = function(x) x)
)

The methods in A are public in B

B$new()
#> <B>
#>   Inherits from: <A>
#>   Public:
#>     clone: function (deep = FALSE)
#>     foo1: function (x)
#>     foo2: function (x)
#>     foo3: function (x)
#>     foo4: function (x)
#>     hello: function (x)
#>   Private:
#>     world: function (x)

Is there any way to avoid public methods from A being public in B? It's not a big problem, it's just that when e.g. there's a class A with a lot of methods, and B has very few, the user sees a lot of methods from the inherited class (A) and very few from B, sort of "polluting" the focus of the target class B

thanks!

wch commented 5 years ago

Sorry for taking so long to respond! There isn't a way to make those methods private in B -- if they became private, then a user couldn't count on B being an implementation of A.

I think you could make a print method that hid the inherited methods, by comparing environment(foo1) with the .__enclos_env__ -- if they match, then the method is not inherited.

sckott commented 5 years ago

okay, thanks