关于r:如何在动态扩展引用类时控制继承

How to control inheritance when dynamically extending Reference Classes

在WebCrawler/WebCraper设置中,我希望动态扩展我的基本引用类URL,以便能够为各自的主机/域编写特定的方法。为了清楚起见,动态地说,我的意思是"遇到新域时自动生成类定义(例如,类URL_something.com,它将从类URL继承)"。

有个办法,唯一的问题是我的类WebPage希望字段URL的值是类URL的值。它将接受类URL_something.com的对象,因为它继承了类URL的对象,但实际上将该对象转换为类URL的实例。所以我失去了它实际上属于URL_something.com类的信息。

你知道我怎样才能避免丢失那些重要的信息吗?

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
setRefClass(Class="URL", fields=list(x="character"))
setRefClass(Class="WebPage", fields=list(url="URL"))

obj <- new("WebPage", url=new("URL", x="http://www.something.com/home/index.html"))
obj$url

# Method would recognize that there is no class 'URL_something.com'
# yet and thus create it:
setRefClass(Class="URL_something.com", contains="URL")

# Another method would take care of mapping field values to
# an instance of the new class:
> url.obj <- new("URL_something.com", x="http://www.something.com/home/index.html")
> inherits(url.obj,"URL")
[1] TRUE

> obj$url <- url.obj
> class(obj$url)
[1]"URL"
# So I lose the information that it was actually of class"URL_something.com"


了解马丁所说的(见上面的评论):R 2.14.0修正了我上面描述的内容。