a beginner, beginners question

a beginner, beginners question

Post by klau » Thu, 20 Mar 2008 19:40:10


Hello,

I'm trying to learn python programming and so far so good. However when
trying to master the oop side I ran into a small problem.

I think I've done everything ok as outlined below. But I just don't
understand why the `method' of `class' example isn't printing any of the
variables that I have set earlier on ? Could someone please explain to me
what it is I am doing wrong ?

Thank you so much !

#!/usr/bin/env python

class example:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar

def method(self):
print "method ... :"
print self.foo
print self.bar


if __name__ == "__main__":
obj = example
obj.foo = "var1"
obj.bar = "var2"
obj.method
 
 
 

a beginner, beginners question

Post by Tim Chas » Thu, 20 Mar 2008 19:57:04

> class example:

This makes "obj" a synonym for "example". You want to
instantiate your "example" class with

obj = example("Some foo", "Some Bar")


which then makes these two lines either unneeded or an
overwriting of the initialization


and this returns a function, not the results of the function.
You need to call it

obj.method()

-tkc

 
 
 

a beginner, beginners question

Post by John Machi » Thu, 20 Mar 2008 20:09:27


What book or online tutorial are using that doesn't lead you to
express that as:
class Example(object):
??


To see what is happening here, do:
print repr(obj)
You need to CALL the class:
obj = example()

This expression produces the method itself, then throws it away.
You need to CALL the method:
obj.method()

HTH,
John
 
 
 

a beginner, beginners question

Post by klau » Thu, 20 Mar 2008 20:17:12


Ok thank you for elaborating I think I've got it.

Thnkx. !