File: ggproto.Rd

package info (click to toggle)
r-cran-ggplot2 3.4.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 8,748 kB
  • sloc: sh: 15; makefile: 5
file content (82 lines) | stat: -rw-r--r-- 2,393 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ggproto.r
\name{ggproto}
\alias{ggproto}
\alias{ggproto_parent}
\alias{is.ggproto}
\title{Create a new ggproto object}
\usage{
ggproto(`_class` = NULL, `_inherit` = NULL, ...)

ggproto_parent(parent, self)

is.ggproto(x)
}
\arguments{
\item{_class}{Class name to assign to the object. This is stored as the class
attribute of the object. This is optional: if \code{NULL} (the default),
no class name will be added to the object.}

\item{_inherit}{ggproto object to inherit from. If \code{NULL}, don't
inherit from any object.}

\item{...}{A list of members in the ggproto object.}

\item{parent, self}{Access parent class \code{parent} of object \code{self}.}

\item{x}{An object to test.}
}
\description{
Construct a new object with \code{ggproto()}, test with \code{is.ggproto()},
and access parent methods/fields with \code{ggproto_parent()}.
}
\details{
ggproto implements a protype based OO system which blurs the lines between
classes and instances. It is inspired by the proto package, but it has some
important differences. Notably, it cleanly supports cross-package
inheritance, and has faster performance.

In most cases, creating a new OO system to be used by a single package is
not a good idea. However, it was the least-bad solution for ggplot2 because
it required the fewest changes to an already complex code base.
}
\section{Calling methods}{

ggproto methods can take an optional \code{self} argument: if it is present,
it is a regular method; if it's absent, it's a "static" method (i.e. it
doesn't use any fields).

Imagine you have a ggproto object \code{Adder}, which has a
method \code{addx = function(self, n) n + self$x}. Then, to call this
function, you would use \code{Adder$addx(10)} -- the \code{self} is passed
in automatically by the wrapper function. \code{self} be located anywhere
in the function signature, although customarily it comes first.
}

\section{Calling methods in a parent}{

To explicitly call a methods in a parent, use
\code{ggproto_parent(Parent, self)}.
}

\examples{
Adder <- ggproto("Adder",
  x = 0,
  add = function(self, n) {
    self$x <- self$x + n
    self$x
  }
 )
is.ggproto(Adder)

Adder$add(10)
Adder$add(10)

Doubler <- ggproto("Doubler", Adder,
  add = function(self, n) {
    ggproto_parent(Adder, self)$add(n * 2)
  }
)
Doubler$x
Doubler$add(10)
}