OOP

D

demon_slayer2839

Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.
 
B

beliavsky

Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me?

Maybe Part VI, "Classes and OOP", of the book "Learning Python", 2nd
edition, by Lutz and Ascher. Both the motivation for OOP and its
implementation in Python are discussed, in about 100 pages.
 
C

Charles Krug

Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.

"Learning Python" (Lutz/Ascher) has a good discussion of the basics.

Unfortunately, most of the OOP writings I've read fall into two
catagories: Trivial examples where you say, "But why Bother??" and
examples that you don't understand until you've some OO design under
your belt and can understand what it's all good for.

Objects are, at the end of the day, data and the accompanying methods.
Once you've read the various tutorials take a stab at converting a
problem you know well into objects.

You'll get it wrong at first. Most everyone does. Don't sweat it.
Eventually, you'll just "get" it.
 
J

Jeremy Bowers

Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.

The biggest problem with understanding Object Orientation is that it is
only a net gain, even when using something as nice as Python, when you
pass the trivial.

If you're looking at provided examples of OO that fits on a screen or two
and going "And so what...?", I'd actually consider that a sign of
comprehension, not a bad thing. (No sarcasm.)

It only goes past "And so what...?" when you get into larger programs.

One example that exists in the Python library and has a lot of code
available on line is the urllib2 library. (Unfortunately, that is
something of a complicated bit of code and you're almost better off just
listening to what I'm going to say here than actually looking at the
code :) )It uses an OO pattern called the "template" pattern, where you
bundle as much code as possible that can be used generally into a
"superclass", and inherit and specialize when you need to do something
specific.

When you want to send an HTTP request, and do something useful with the
results, you create your own request subclass. As a result of using it,
the superclass does all of it's stuff, in this case making the connection
and basic parsing of the results, so you don't have to. The superclass
then calls into the sub-class's overridden methods, based on what happened
with the request. For instance, if you are writing an RSS retriever and
the retrieval results in a 302 code, "Moved Permanently", the superclass
will call self.error_302(), and the RSS reader can then update its
personal database of RSS file locations.

OO consists structurally of the code+data combination; OO consists
*practically* of each of these little techniques, like I gave in the
previous paragraph, adding together and making things easy. None of them
are *impossible* with non-OO code, merely harder to write, but the
cumulative easing effect is quite significant.

You're probably closer to understanding the theory than you think; now you
just need to use it for a while, with an active, open mind probing for
ways to make your programming life easier. Only that will bring deeper
understanding, or maybe reading other's code if you're dedicated. You
might also look online for some of the "Design Patterns", which aren't
worth worshiping but provide a concise description of some of the other
things that OO makes easier than the alternatives.

(You may also be interested in this essay I wrote:

http://www.jerf.org/writings/bowersLaw.html

One of the problems OO faced in general, especially the late 80s and most
of the 90s, was prematurely jumping to dogma before there was adequate
community experience to formulate a *good* dogma; even today there are a
lot of "OO experts" who would take extensive exception to both this post
and that essay, even though I'm pretty sure that facts and experience are
on my side :) . The old dogma lives on, even as many communities like
Python, Ruby, and the Testing Methodology folk are formulating better
ones. The reality of OO is that it is a rich and highly varied *family* of
techniques, which may also not be helping if you try to learn from
multiple sources; that essay tries to explore the common thread behind all
of those techniques, and explain why it is the common thread.)
 
K

Kartic

The Great '(e-mail address removed)' uttered these words on 4/28/2005
1:34 PM:
Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.

I thought the Object Orientation chapter (Chapter 5) of Python in a
Nutshell by Alex Martelli, gave a good overview for Classes in Python.
Please take a peek at it and see if it helps you any.

Thanks,
-Kartic
 
S

Scott Robinson

"Learning Python" (Lutz/Ascher) has a good discussion of the basics.

Unfortunately, most of the OOP writings I've read fall into two
catagories: Trivial examples where you say, "But why Bother??" and
examples that you don't understand until you've some OO design under
your belt and can understand what it's all good for.

Objects are, at the end of the day, data and the accompanying methods.
Once you've read the various tutorials take a stab at converting a
problem you know well into objects.

You'll get it wrong at first. Most everyone does. Don't sweat it.
Eventually, you'll just "get" it.

[Note: this is just the start of an explanation. If you don't
understand OOP, just try programming that way (yes, I got it wrong to
see my usage of "Wally objects").

This is something I thought of awhile ago, and wondered where I could
use it. My background is a hardware guy who first learned spaghetti
coding in basic on 8-bits, received the wisdom of modular programming
when learning assembler, then much later tried his hand teaching
himself python. Those from other backgrounds may be amused at my
naivete.]

I've been trying to figure out the "Dilbert" view of OOP.

My first objects were like C types:

class Super_object:
pass

Consider this the Wally object.

Wally=Super_object():

Things get put on his desk:

Wally.MeetingActionItems=[1,2,3]

And stay there. At first, this seems great. It gives you plenty of
desks to store data on.

After a while, you might paint yourself into a corner (such as wanting
to append to lists, but later wish to hard limit the number of
entries, thus needing to change from a list to an overloaded object).
This brings the Dilbert object. You can put things on Dilbert's desk,
but unlike Wally, he can actually notice the objects, manage them, and
do some work on it.

Class Dilbert_object:
__init__(self):
ActionItems=[]
def AddItems(self,items):
self.ActionItems.append(items)

def DoAction(self):
return self.ActionItems.pop()

Ok, I admit that this just looks like yet another getter and setter.
Maybe this is an Asok object and Dilbert would realize that the Boss
doesn't remember everything on his desk, so we change it to:

Class Dilbert_object:
__init__(self):
ActionItems=[]
def AddItems(self,items):
self.ActionItems.append(items)
if len(self.ActionItems)>10:
self.ActionItems.pop(0)
def DoAction(self):
return self.ActionItems.pop()

Since OOP dogmatists insist that inheritance is vital to OOP, we
include the Alice object. Alice can do everything Dilbert can do, and
then some. To include Dilbert's skills we simply include

Class Alice_object(Dilbert_object):

To add new things to the Alice object:

Class Alice_object(Dilbert_object):
def FistOfDeath(self):
import os
os._exit(0)


The critical thing is that you can now let Dilbert manage your data.
That's one of the main reasons for inventing computers anyway, to
manage data. So write subprograms (objects) that do your work for
you, and work as thanklessly as Dilbert, and then try to concentrate
on debugging the big picture.

Scott
 
D

Dave Cook

I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.

I haven't seen anything specifically written for Python that gets much
beyond the mechanics.

One of the best books I've read on OOP is _Smalltalk, Objects, and Design_
by Chamond Liu. It would be nice to have something like that for Python.

Dave Cook
 
M

monkey

Although I am a newbie in programming, I read from a java book (in my native
language) saying that the purpose of Object Oriented Programming are:

1. Use a real world concept in constructing program (here everything are
objects with there properties and methods/actions);

2. Simplify coding;

3. and most important, faciliate the reuse of code (class, function, etc.)
 
K

Kent Johnson

Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.

You might be interested in this essay which gives some motivation for simple use of classes:
http://www.pycs.net/users/0000323/stories/15.html

Kent
 
G

GMane Python

As with most things, you have to understand 'why' you want to do something
before you can really understand how it applies.

Ok. Go to amazon. They've setup a 'shopping cart'. That cart is made of
variables, name, cred.card num, items, quantity of items, ship-to address,
state, shipping cost, shipping type, tax (if applicable), etc. Ok. If you
have a program and want this info, ok, you could set up variables for all of
them.

What if you now have 2 shopping carts? How do you double the variables?
What if you now have 1000 shopping carts? How do you scale your programming
so what works for 1 works for 1000?

OOP allows you to create a 'structure' of the variables, and when someone
enters their name in a field and hits, 'add to cart' , abstractly, you'll
have a structure in your program like:

User = ShoppingCartClass()

Now, you defined User to be an object of ShoppingCartClass.

Now, methods are pre-defined actions. You might have:
..Checkout()
..DeleteItem()
..AddItem()

and of course inside the parenthesis, you'd have relevent info. for the
routine.

So maybe you'd do:
User = ShoppingCartClass()
User.AddItem(sku=5)
User.DeleteItem(sku=22)
User.CheckOut(State='CT', CredCard='Visa', CredNum='1234-5678-8765-4321')

So, there's the why. This just barely scratches the surface. hope I didn't
confuse you.

-Dave
 
D

Dave Rose

So, I forgot the last part of my example that might gel in your mind why
Objects are useful in certain situations. Ok so you maybe followed my example
of the shopping cart. Let's just forget for a moment the use for shopping
carts is for websites. Let's just say you were going to write the lines
directly into Python, like maybe at the IDLE interpreter. Like maybe you're
testing the functionality of the routine for correctness, not actual
implementation.

You have a ShoppingCartClass(), and three users-> Dave, Tommy, Bryan.
ShoppngCartClass() has 3 methods:
..AddItem()
..RemoveItem()
..CheckOut()

These are really just 'def' routintes you write in the class to do some action
or calculation. Here, we want to either add an item to 'the cart', remove
one, or finalize the order.

In the interpreter, you could do this. Define 3 users of the
ShoppingCartClass.

Dave = ShoppingCartClass()
Tommy = ShoppingCartClass()
Bryan = ShoppingCartClass()


Ok. Now you could do different things to each:

Dave.AddItem(sku=5)
Tommy.AddItem(sku=77)
Tommy.AddItem(sku=12)
Tommy.RemoveItem(sku=12)
Dave.CheckOut(state=CT, ccard='visa', ccardnum='1234-5678-8765-431')
Tommy.CheckOut(stsate=RI, ccard='mastercard', ccardnum='431-123-4321-1234')
Bryan.CancelOrder()

so, if you were then to take account of what you had, you'd know:
Dave has item SKU=5
Tommy has item SKU=77
Bryan has his order cancelled.

This is still very hard-coded. You could abstract, or maybe variablize,
things more. Let's try:

You can mix classes with say dictionaries, to make their use in routines more
beneficial.

So, you could have:

user = “Daveâ€
ShoppingCart={}
ShoppingCart[user] = ShoppingCartClass()
user = “Tommyâ€
ShoppingCart[user] = ShoppingCartClass()
user = “Daveâ€
ShoppingCart[user].AddItem(sku=55)
user = “Tommyâ€
ShoppingCart[user].CheckOut( ... )
ShoppingCart[“Daveâ€].CheckOut( ... )

Putting the classes in the dictionary allow you to use names from things like
fields, config files, text files, TextControls in my favorite program
wxPython, etc.

If you can wrap your mind around this, you're well on your way to using OOP I
believe. If not, , don't give up. I'm just a python/programming newbie and
maybe missed the boat completely with my posting.

-Dave
 
G

GMane Python

So, I forgot the last part of my example that might gel in your mind why
Objects are useful in certain situations. Ok so you maybe followed my
example of the shopping cart. Let's just forget for a moment the use for
shopping carts is for websites. Let's just say you were going to write the
lines directly into Python, like maybe at the IDLE interpreter. Like maybe
you're testing the functionality of the routine for correctness, not actual
implementation.



You have a ShoppingCartClass(), and three users-> Dave, Tommy, Bryan.

ShoppngCartClass() has 3 methods:

..AddItem()

..RemoveItem()

..CheckOut()



These are really just def routintes you write in the class to do some action
or calculation. Here, we want to either add an item to 'the cart', remove
one, or finalize the order.



In the interpreter, you could do this. Define 3 users of the
ShoppingCartClass.



Dave = ShoppingCartClass()

Tommy = ShoppingCartClass()

Bryan = ShoppingCartClass()





Ok. Now you could do different things to each:



Dave.AddItem(sku=5)

Tommy.AddItem(sku=77)

Tommy.AddItem(sku=12)

Tommy.RemoveItem(sku=12)

Dave.CheckOut(state=CT, ccard='visa', ccardnum='1234-5678-8765-431')

Tommy.CheckOut(stsate=RI, ccard='mastercard', ccardnum='431-123-4321-1234')

Bryan.CancelOrder()



so, if you were then to take account of what you had, you'd know:

Dave has item SKU=5

Tommy has item SKU=77

Bryan has his order cancelled.



This is still very hard-coded. You could abstract, or maybe variablize,
things more. Let's try:



You can mix classes with say dictionaries, to make their use in routines
more beneficial.



So, you could have:



user = "Dave"

ShoppingCart={}

ShoppingCart[user] = ShoppingCartClass()

user = "Tommy"

ShoppingCart[user] = ShoppingCartClass()

user = "Dave"

ShoppingCart[user].AddItem(sku=55)

user = "Tommy"

ShoppingCart[user].CheckOut( ... )

ShoppingCart["Dave"].CheckOut( ... )



Putting the classes in the dictionary allow you to use names from things
like fields, config files, text files, TextControls in my favorite program
wxPython, etc.



In a class, you can have a variable 'total' and you can have a variable
'self.total'. The first is just accessible from within the structure of the
class. The latter is accessible from outside the class. So, using a class
with the variable self.total, you can from outside the class say:



print ShoppingCart["Dave"].total



to get the value of the variable self.total. (That had me buggered for a
while ..... )



If you can wrap your mind around this, you're well on your way to using OOP
I believe. If not, , don't give up. I'm just a python/programming newbie
and maybe missed the boat completely with my posting.



Another quite important part I didn't even mention was sub-classing. That's
taking a class, and 'inheriting' it's code to your class as a base, then you
can re-write or adddifferent methods. But, first I think it's important to
understand how to have several instances of a single class running in
memory, each with different values for the defined variables. I'll let
someone else talk about that.



-Dave
 
S

Steve Holden

GMane said:
So, I forgot the last part of my example that might gel in your mind why
Objects are useful in certain situations. Ok so you maybe followed my
example of the shopping cart. Let's just forget for a moment the use for
shopping carts is for websites. Let's just say you were going to write the
lines directly into Python, like maybe at the IDLE interpreter. Like maybe
you're testing the functionality of the routine for correctness, not actual
implementation.
[good introductory class stuff snipped]
In a class, you can have a variable 'total' and you can have a variable
'self.total'. The first is just accessible from within the structure of the
class. The latter is accessible from outside the class. So, using a class
with the variable self.total, you can from outside the class say:



print ShoppingCart["Dave"].total



to get the value of the variable self.total. (That had me buggered for a
while ..... )
Thanks for the smile this gave me. We all get to this stage periodically
when programming.
If you can wrap your mind around this, you're well on your way to using OOP
I believe. If not, , don't give up. I'm just a python/programming newbie
and maybe missed the boat completely with my posting.
Well maybe you did, but you actually managed to demonstrate important
parallels between namespaces and dictionaries in Python.
Another quite important part I didn't even mention was sub-classing. That's
taking a class, and 'inheriting' it's code to your class as a base, then you
can re-write or adddifferent methods. But, first I think it's important to
understand how to have several instances of a single class running in
memory, each with different values for the defined variables. I'll let
someone else talk about that.
As indeed they almost inevitably will :)

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,237
Messages
2,571,190
Members
47,827
Latest member
wyton

Latest Threads

Top