'generic' 和 'method' 的区别?
Difference between 'generic' and 'method'?
我注意到 R 中的以下函数有两个略有不同的class说明:
sloop::ftype(t.test)
#> [1] "S3" "generic"
sloop::ftype(t.data.frame)
#> [1] "S3" "method"
由 reprex package (v1.0.0)
创建于 2021-04-21
一个是 'generic',一个是 'method',但我很难区分这两者:我对 'generic' 的理解是 一种方法 - 具体来说,一种根据其 class.
作用于输入对象的方法
一个方法实现一个泛型(或者,在更技术层面上,一个方法被泛型通过UseMethod
调用)。
即泛型函数调用UseMethod
;它可能看起来像这样:
foo = function (x, ...) UseMethod('foo')
而方法是一个为特定S3实现泛型的函数class;例如:
foo.bar = function (x, ...) message('class of x is bar!')
我注意到 R 中的以下函数有两个略有不同的class说明:
sloop::ftype(t.test)
#> [1] "S3" "generic"
sloop::ftype(t.data.frame)
#> [1] "S3" "method"
由 reprex package (v1.0.0)
创建于 2021-04-21一个是 'generic',一个是 'method',但我很难区分这两者:我对 'generic' 的理解是 一种方法 - 具体来说,一种根据其 class.
作用于输入对象的方法一个方法实现一个泛型(或者,在更技术层面上,一个方法被泛型通过UseMethod
调用)。
即泛型函数调用UseMethod
;它可能看起来像这样:
foo = function (x, ...) UseMethod('foo')
而方法是一个为特定S3实现泛型的函数class;例如:
foo.bar = function (x, ...) message('class of x is bar!')