2016-07-19 9 views
5

Szukam odpowiednika słowa kluczowego "ja" Pythona lub słowa kluczowego "this" java w R. W poniższym przykładzie robię obiekt S4 z metody inny obiekt S4 i trzeba przekazać mi wskaźnik. Czy jest coś w tym języku, aby pomóc mi to zrobić?Odpowiednik "this" lub "self" w 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 
    } 
) 
) 

mogę to zrobić za pomocą metody wolnostojącej ale miałem nadzieję na miłą obiektowego sposobu prowadzenia tej operacji w R. Dzięki

+0

Jest to 'klasa referencyjna' (? 'ReferenceClasses' lub' setRefClass') zamiast S4 klasa per se ('Classes','? Metody "). Od? ReferenceClasses, patrz '.self'. –

Odpowiedz

4

klasy Reference (RC) obiekty są w zasadzie S4 obiektów, które owijają środowisko. Środowisko przechowuje pola obiektu RC i jest ustawione jako otaczające środowisko jego metod; tak niewykwalifikowane odniesienia do identyfikatorów pól wiążą się z polami instancji. Udało mi się znaleźć obiekt .self w środowisku, które według mnie jest dokładnie tym, czego szukasz.

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) 

Więc rozwiązanie jest:

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

to jest świetne! dzięki – jamesatha

Powiązane problemy