• anonymous
Hi fellow OCW student, I have very fundamental questions about programming in general. I'd like to use a simple example as follows: class Square(Shape): def __init__(self, h): "h: length of side of the square" self.side = float(h) ===>> here, why should I use self.side instead of using just side = float(h)? I kind of understand why, but not 100%.
Computer Science
  • Stacey Warren - Expert
Hey! We 've verified this expert answer for you, click below to unlock the details :)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
  • schrodinger
I got my questions answered at in under 10 minutes. Go to now for free help!
  • anonymous
The `self.` part indicates that the variable is a member of the class and not a local variable. Suppose you try to write your code like this: class Square(Shape): def __init__(self, h): side = float(h) What is side? Is side a local variable, usable only inside the `__init__` function? Or is it a member of the class? To avoid this confusion, you'll need to specifically say that the variable is a class member by putting `self.` in front of the variable. It also depends on the language (for example, in C++ you may, but are not required to, use `this->` to access member variables).

Looking for something else?

Not the answer you are looking for? Search for more explanations.