why is "self" used in OO-Python?

satoru torainLight at gmail.com
Sun Jul 13 08:35:01 EDT 2008


On Jul 13, 12:32 am, ssecorp <circularf... at gmail.com> wrote:
> I first learned about OO from Java.
>
> I much prefer to program in Python though.
>
> However I am consufed about 2 things.
>
> 1. Why do I have to pass self into every method in a class? Since I am
> always doing why cant this be automated or abstracted away?
> Are the instances where I won't pass self?
> I imagine there is some tradeoff involved otherwise it would have been
> done away with.
>
> 2. self.item instead of getters and setters. I thought one of the main
> purposes of OO was encapsulation. Doesn't messing with internal object-
> representations break this?
> I see how the getters and setters could be just visual clutter and you
> have to add them to every class so it is annoying a bit in the same
> way as self described above.
> However I feel like I want getters and setters when I write classes,
> not sure of the advantages/disadvantages though.
> Only looking at the documentation of a Python-class, will internal
> representations be provided?
>
> If I have a class:
>
> class Stack(object):
>     def __init__(self, *items):
>         self.stack = list(items)
>
>     def append(self, item):
>         self.stack.append(item)
>
>     def pop(self):
>         return self.stack.pop()
>
> I can get to see the stack with var.stack but then why even implement
> append when I could do self.stack.append(x) etc.
> That way you could do away with OO completely. So why let people
> access the main attribute but not let them manipulate it?
> Makes more sense to draw the line to not access any attributes at all
> no?
i think the following article may be helpful to you.
"Introduction to OOP with Python"
http://www.voidspace.org.uk/python/articles/OOP.shtml#id34



More information about the Python-list mailing list