2017-01-07 2 views
0

I definierten Klasse multiset wie folgt:R: define Klasse als Liste der Klassen

### 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) 

Jetzt will ich habe Klasse multisets, die nur ein list von multiset Klassen sein wird.

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

Problem mit meiner Definition ist, dass es jede Liste eingefügt ermöglicht

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

werden Wie würde ich multisets enthalten nur Liste der Objekte mit Klasse multiset beschränken?

Antwort

0

Prototyp liefert Standarddaten für die in der Darstellung angegebenen Steckplätze. prototype Funktion wird verwendet, um Standarddaten zu setzen

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) 
Verwandte Themen