pearselab / r-intro-aspri951

r-intro-aspri951 created by GitHub Classroom
0 stars 1 forks source link

defining a class #1

Open aspri951 opened 8 years ago

aspri951 commented 8 years ago

I'm still trying to understand the concept of classes. Intuitively, I would define the properties of a class, and then go to a group of objects and see if they belong in that class. In other words, I intuitively want to say a) my class is "cat" and b) the properties of "cat" are 1) canine teeth, 2) retractile claws, etc. THEN I go look at a specific object, and if that object has these properties, then it belongs in class "cat" (deductive logic). So I am trying to write code along the lines of class(cat) <- c("canines", "claws", ...). It seems that this is NOT what R is doing? Rather than defining a class and putting objects in it (deduction), your example of class dog takes the opposite approach (induction: defining the properties of an object and using the specific object to define a class--Dexter has a tail etc. therefore all dogs have tails, so class ,<- whatever properties Dexter has)?

... long story short, can you only define a class by giving it an instance/example?

willpearse commented 8 years ago

Sadly, no. This is a very reasonable thing to want to do, but alas, no.

It is perfectly possible in R for two things of the same class to have different slots. For example:

one <- list(x=10, y=30)
class(one) <- "example"
two <- list(a="1234", f="asdfg")
class(two) <- "example"

...R won't give an error, but this is not a very good thing! This is why I recommend using constructors - R won't check that the instances of your class are all comparable. Does that make sense?

I agree that this is a silly way to implement classes - I will be going through why classes are so silly in R in the next session.