R/py-classes.R

%py_class%

Make a python class constructor

Description

Make a python class constructor

Usage

 
spec %py_class% body 

Arguments

Arguments Description
spec a bare symbol MyClassName, or a call MyClassName(SuperClass)
body an expression that can be evaluated to construct the class methods.

Value

The python class constructor, invisibly. Note, the same constructor is also assigned in the parent frame.

Examples

library(keras)
 
MyClass %py_class% { 
  initialize <- function(x) { 
    print("Hi from MyClass$initialize()!") 
    self$x <- x 
  } 
  my_method <- function() { 
    self$x 
  } 
} 
 
my_class_instance <- MyClass(42) 
[1] "Hi from MyClass$initialize()!"
my_class_instance$my_method() 
[1] 42
MyClass2(MyClass) %py_class% { 
  "This will be a __doc__ string for MyClass2" 
 
  initialize <- function(...) { 
    "This will be the __doc__ string for the MyClass2.__init__() method" 
    print("Hi from MyClass2$initialize()!") 
    super$initialize(...) 
  } 
} 
 
my_class_instance2 <- MyClass2(42) 
[1] "Hi from MyClass2$initialize()!"
[1] "Hi from MyClass$initialize()!"
my_class_instance2$my_method() 
[1] 42
reticulate::py_help(MyClass2) # see the __doc__ strings and more! 
 
# In addition to `self`, there is also `private` available. 
# This is an R environment unique to each class instance, where you can 
# store objects that you don't want converted to Python, but still want 
# available from methods. You can also assign methods to private, and 
# `self` and `private` will be available in private methods. 
 
MyClass %py_class% { 
 
  initialize <- function(x) { 
    print("Hi from MyClass$initialize()!") 
    private$y <- paste("A Private field:", x) 
  } 
 
  get_private_field <- function() { 
    private$y 
  } 
 
  private$a_private_method <- function() { 
    cat("a_private_method() was called.\n") 
    cat("private$y is ", sQuote(private$y), "\n") 
  } 
 
  call_private_method <- function() 
    private$a_private_method() 
} 
 
inst1 <- MyClass(1) 
[1] "Hi from MyClass$initialize()!"
inst2 <- MyClass(2) 
[1] "Hi from MyClass$initialize()!"
inst1$get_private_field() 
[1] "A Private field: 1"
inst2$get_private_field() 
[1] "A Private field: 2"
inst1$call_private_method() 
a_private_method() was called.
private$y is  'A Private field: 1' 
inst2$call_private_method() 
a_private_method() was called.
private$y is  'A Private field: 2' 

See Also

https://keras.rstudio.com/articles/new-guides/python_subclasses.html