2016-07-19 5 views
5

나는 python의 'self'키워드 또는 java의 'this'키워드와 유사한 R을 찾고 있습니다. 다음 예제에서는 메소드에서 S4 객체를 만들고 있습니다. 다른 S4 개체 및 자신에게 포인터를 전달해야합니다. 이 일을 도와 줄 수있는 언어가 있습니까?'this'또는 'self'에 해당하는 R

MyPrinter <- setRefClass("MyPrinter", 
    fields = list(obj= "MyObject"), 
    methods = list(
    prettyPrint = function() { 
     print(obj$age) 
     # do more stuff 
    } 
) 
) 

MyObject <- setRefClass("MyObject", 
    fields = list(name = "character", age = "numeric"), 
    methods = list(
    getPrinter = function() { 
     MyPrinter$new(obj=WHAT_GOES_HERE) #<--- THIS LINE 
    } 
) 
) 

나는 독립형 방법으로이 작업을 수행 할 수 있지만 S4는 랩 객체

+0

이것은 "기준 클래스 '는 (?'ReferenceClasses' 또는'setRefClass')보다는 S4 클래스 자체 ('Classes', '? 방법'). ? ReferenceClasses에서, .self를 참조하십시오. –

답변

4

참조 클래스 (RC) 객체가 기본적으로 있습니다 R. 감사에서이 작업을 수행의 좋은 객체 지향 방법을 기대했다 환경. 환경은 RC 객체의 필드를 포함하며 해당 메소드의 둘러싸는 환경으로 설정됩니다. 이것이 필드 식별자에 대한 규정되지 않은 참조가 인스턴스의 필드에 바인딩하는 방법입니다. 나는 정확하게 당신이 찾고있는 환경이라고 믿는 환경에 앉아있는 .self 개체를 찾을 수있었습니다.

x <- MyObject$new(); ## make a new RC object from the generator 
x; ## how the RC object prints itself 
## Reference class object of class "MyObject" 
## Field "name": 
## character(0) 
## Field "age": 
## numeric(0) 
is(x,'refClass'); ## it's an RC object 
## [1] TRUE 
isS4(x); ## it's also an S4 object; the RC OOP system is built on top of S4 
## [1] TRUE 
slotNames(x); ## only one S4 slot 
## [1] ".xData" 
[email protected]; ## it's an environment 
## <environment: 0x602c0e3b0> 
environment(x$getPrinter); ## the RC object environment is set as the closure of its methods 
## <environment: 0x602c0e3b0> 
ls([email protected],all.names=T); ## list its names; require all.names=T to get dot-prefixed names 
## [1] ".->age"  ".->name"  ".refClassDef" ".self"  "age"   "field" 
## [7] "getClass"  "name"   "show" 
[email protected]$.self; ## .self pseudo-field points back to the self object 
## Reference class object of class "MyObject" 
## Field "name": 
## character(0) 
## Field "age": 
## numeric(0) 

그래서 용액이다 :

MyObject <- setRefClass("MyObject", 
    fields = list(name = "character", age = "numeric"), 
    methods = list(
     getPrinter = function() { 
      MyPrinter$new(obj=.self) 
     } 
    ) 
) 
+0

이것은 아주 좋습니다! 감사 – jamesatha