davor davor - 1 month ago 17
Python Question

Property decorator in S4 objects (R)

In python one can use the

@property
decorator on a method of a class which allows it to be used as a property. So instead of
car.tyres()
you write
car.tyres
. Each time you access
car::tyres
, some method will run and return the value - according to the OO paradigm. In this way, you don't need to store any information in the object, but compute it on access (which allows a trade-off between memory and CPU time).

I am having now a similar S4 object in R and wonder whether


  1. this is possible in R for S4 objects and

  2. whether this is good practice in R?



As for (2) I have a feeling that a more common way to do this in R is to write a generic function
tyres()
and then do
tyres(car)
. But that doesn't seem as OO-programming to me. Can someone elaborate?

Answer

I never found a way to do this in S4. But this is certainly possible in R6 objects. It is called Active binding.

R6 objects allow accessing attributes and calling member methods directly from the object instance with the $operator, similar to other OOP languages like Java and C++. This allows for much more natural OOP code in R than it is possible with S3 and S4 objects.