Why create new classes in R?
I know that you can create new classes in R, but why would you want to? I've thought of two reasons:
- You can use the
is.
function to test whether an object belongs to a particular class (classifications of objects) - To only allow certain classes of entries into slots of an object (e.g., only a string for the surnmane and only a number for a zip code in the pers开发者_运维百科on class).
I haven't thought of situations where these benefits couldn't be achieved fairly easily by other means or when they'd really be useful.
I hope that this isn't too open ended and more concrete examples how one might use defining classes would be great. Thanks for any thoughts.
Its called Object-Oriented programming. Look it up, but in short:
Objects encapsulate behaviour - eg the behaviour of the 'print' method for a class is specific to that class. You can then keep the code for that method on that class separate from other code. You then only have to tell your users to "print" the thing - which is something they already do - and they get a nicely custom printed version of your thing, without having to use a special print function, like "printMyThing(thing)".
Objects inherit behaviour from their parent classes - eg the 'formula' method for the glm class falls back to the formula method for the lm class (not sure if this is true, but its just for illustration.
In short, its a Good Thing.
精彩评论