R:将类定义为类列表

时间:2017-01-07 10:38:01

标签: r list oop

我将课程multiset定义如下:

### MULTISET ###
setClass('multiset'
         ,slots=c(
            obj="character",
            amount="numeric"))

# init multiset#
createMultiset = function(object,val=numeric(0)){
  mset = new('multiset',obj=object,amount=val)
  return(mset)
}

# example
m1 <- createMultiset('person',12)

现在我想要上课multisets,这只是listmultiset课程。

### LIST OF MULTISETS ###
setClass("multisets",slots=c(objects='list'), contains='multiset')

我的定义问题是它允许插入任何列表

new('multisets',objects=list('a',1))

如何限制multisets仅包含类multiset的对象列表?

1 个答案:

答案 0 :(得分:0)

prototype为表示中指定的插槽提供默认数据。 prototype函数用于设置默认数据

setClass('multiset',
         representation = representation(obj = "character", amount = "numeric"),
         prototype = prototype(obj = 'hi', amount = 0))

getClass('multiset')
# Class "multiset" [in ".GlobalEnv"]
# 
# Slots:
#   
#   Name:        obj    amount
# Class: character   numeric

new("multiset")
# An object of class "multiset"
# Slot "obj":
#   [1] "hi"
# 
# Slot "amount":
#   [1] 0

# init multiset#
setMethod(f = 'initialize', 
          signature = 'multiset', 
          definition =  function(.Object, ..., amount = numeric(0)){
            print('you just initialized the class - multiset')
            callNextMethod(.Object, ..., amount = amount)
          })
new('multiset', amount = 2)
# [1] "you just initialized the class - multiset"
# An object of class "multiset"
# Slot "obj":
#   [1] "hi"
# 
# Slot "amount":
#   [1] 2


setClass('multisets', 
         contains = 'multiset',
         representation = representation(objects = 'list'),
         prototype = prototype(objects = list('bye')))

new('multisets', objects = list('a',1))

# An object of class "multisets"
# Slot "objects":
#   $obj
# [1] "a"
# 
# $amount
# [1] 1
# 
# 
# Slot "obj":
#   [1] "hi"
# 
# Slot "amount":
#   [1] 0

# define class SS
setClass('SS', representation = representation(money = 'numeric'))

# define class DB which is a subclass of both multiset and SS
setClass('DB', contains = (c('SS', 'multiset')))
a1 <- new('multiset', obj = 'hello')
b1 <- new('SS', money = 50)

new('DB', a1, b1)
# [1] "you just initialized the class - multiset"
# An object of class "DB"
# Slot "money":
#   [1] 50
# 
# Slot "obj":
#   [1] "hello"
# 
# Slot "amount":
#   numeric(0)