Objects in Python

S

shaun

I'm having an issue its my first time using python and i set up a class one of the methods is supposed to return a string but instead returns:

<bound method Param.returnString of <Param.Param instance at 0x00C
389E0>>

Im very new to python and the object orientated feature doesnt seem to be as well put together as Java. Can anyone help with this problem?
 
J

Joel Goldstick

I'm having an issue its my first time using python and i set up a class one of the methods is supposed to return a string but instead returns:

<bound method Param.returnString of <Param.Param instance at 0x00C
389E0>>

Im very new to python and the object orientated feature doesnt seem to be as well put together as Java. Can anyone help with this problem?

It looks like you didn't add parens to the end of your call. Show us
your code. with the traceback
 
J

Jussi Piitulainen

shaun said:
I'm having an issue its my first time using python and i set up a
class one of the methods is supposed to return a string but instead
returns:

<bound method Param.returnString of <Param.Param instance at 0x00C
389E0>>

Im very new to python and the object orientated feature doesnt seem
to be as well put together as Java. Can anyone help with this
problem?

I bet you are trying to call the method, returnString, without the
parentheses that enclose the parameters (and without any @property
stuff in the class).
'dox'
 
P

Peter Otten

shaun said:
I'm having an issue its my first time using python and i set up a class
one of the methods is supposed to return a string but instead returns:

<bound method Param.returnString of <Param.Param instance at 0x00C
389E0>>

Im very new to python and the object orientated feature doesnt seem to be
as well put together as Java.

It's definitely too early for you to draw conclusions ;)
Can anyone help with this problem?

You have successfully created a bound method, now you need to invoke it:
.... def returnString(self):
.... return "hello"
....<bound method Param.returnString of <__main__.Param object at
0x7facb3a16a50>>'hello'

Unlike some other langages Python does not implicitly invoke functions or
methods. That makes it easy to pass them around like any other object.
 
J

John Gordon

In said:
I'm having an issue its my first time using python and i set up a class one of the methods is supposed to return a string but instead returns:
<bound method Param.returnString of <Param.Param instance at 0x00C
389E0>>

It looks like you're referencing the method object itself, instead of
calling it method. In other words, you've left off the parentheses.

I.e. you're doing something like this:

print my_object.foo

Instead of this:

print my_object.foo()
 
S

shaun

Here is some code:
//////////////////////////This is the object I want to create:
#!/usr/bin/python
import cx_Oracle
import sys
import time
import datetime


class batchParam:

def __init__(self,array):
self.array=array


def breakuparray(self):
for row in self.array:
mer = row[0].ljust(25, ' ')
merc = row[1].ljust(13, ' ')
mertype = row[2]
merloc = row[3]
mercount = row[4]
mersec = row[5]
acq = row[6]



def returnBatch(self):
self.breakuparray()
return "\x01001\x0251.%s%s%s%s%s%s%s%s\x03" % (mer, merc, mertype, merloc, mercount, mersec, acq);


//////////////////////////////////////Here is the script I want to run the object in:


#!/usr/bin/python
import cx_Oracle
import sys
import time
import datetime
sys.path.append("C:\\Documents and Settings\\swiseman\\Desktop")
from batchParam import batchParam

term = sys.argv[1]
batch = sys.argv[2]

con = cx_Oracle.connect('databaseInfo')


cur = con.cursor()
cur.execute("SELECT * FROM SOME_TABLE))

results = cur.fetchall()

batchParam(results)
Batch=batchParam.returnBatch

print Batch

cur.close()

//////////////////////////////////////

Thanks,
Shaun
 
C

Chris Angelico

def breakuparray(self):
for row in self.array:
mer = row[0].ljust(25, ' ')
merc = row[1].ljust(13, ' ')
mertype = row[2]
merloc = row[3]
mercount = row[4]
mersec = row[5]
acq = row[6]

The "for ... in ..." construct is a loop. I'm not sure what you're
trying to accomplish here, but you're taking the last entry in
self.array and unpacking that as a nested array. Perhaps not what you
had in mind.

For what you're doing there, though, a class is overkill. Remember,
Python isn't Java; the most natural way to do everything isn't
necessarily to write a class that unpacks things and packs them up
again in a different way.

ChrisA
 
D

Dave Angel

Here is some code:
//////////////////////////This is the object I want to create:
#!/usr/bin/python
import cx_Oracle
import sys
import time
import datetime


class batchParam:

def __init__(self,array):
self.array=array


def breakuparray(self):
for row in self.array:
mer = row[0].ljust(25, ' ')
merc = row[1].ljust(13, ' ')
mertype = row[2]
merloc = row[3]
mercount = row[4]
mersec = row[5]
acq = row[6]



def returnBatch(self):
self.breakuparray()
return "\x01001\x0251.%s%s%s%s%s%s%s%s\x03" % (mer, merc, mertype, merloc, mercount, mersec, acq);


//////////////////////////////////////Here is the script I want to run the object in:


#!/usr/bin/python
import cx_Oracle
import sys
import time
import datetime
sys.path.append("C:\\Documents and Settings\\swiseman\\Desktop")
from batchParam import batchParam

term = sys.argv[1]
batch = sys.argv[2]

con = cx_Oracle.connect('databaseInfo')


cur = con.cursor()
cur.execute("SELECT * FROM SOME_TABLE))

results = cur.fetchall()

batchParam(results)

This creates an instance of batchParam, but doesn't save it anywhere.
So it's discarded immediately.
Batch=batchParam.returnBatch
This tries to returns a reference to a static method of the class.
Without an object, you won't get access to normal instance methods;
there's no 'self'. And without parentheses, you won't even try to call
the method, right or wrong.

Probably you wanted something like:

obj = batchParam(results) #now obj is an instance
mystring = obj.returnBatch() #calls the method, and saves the
returned string
print mystring
print Batch

cur.close()

Other comments: Don't make the mistake of forcing every class into its
own source file. Unlike java, python has no such restrictions. It also
has ordinary functions, not part of any class. So if several classes
are related, go ahead and put them in a common file. Or keep them
separate, Python doesn't mind.

There are capitalization conventions: class names start with a capital
letter, and source code filenames do not. So the class you've got in
batchParam could be called BatchParam.

Neither of these matter much, but they make it easier for someone else
to see what you were trying to do.

It would also be helpful if you posted the complete error message (with
traceback), so we could more easily guess where in the code the problem
occurs. It can be useful to add a comment in the actual source you
post, since you have line numbers in your editor, and we don't in our
emails. But don't try to get cute with colors, as this is a text
forum. (that last comment may not apply to you, since you already used
a plain-text format for your message)

Python does have classmethod and staticmethod, but that's not usually
what you want, and not here.
 
M

MRAB

On 22/08/12 15:13, shaun wrote:

[snip]
Im very new to python and the object orientated feature doesnt seem to be as well put together as Java. Can anyone help with this problem?

From one Java head to another I suggest you park what you know about
Java and approach Python with a clear mind.

Python is not Java and Java is not Python, that much has become clear.
Python has actually been around longer than Java and contains many
features you will be familiar with, serialization and introspection to
name but two. The whole 'everything is an object' thing is a bit strange
at first but actually it just means that everything you write is wrapped
up in a component that exposes various standard methods and attributes,
you treat functions as Objects and modules as Objects and even your
classes will automagically sprout new attributes and properties, at
least that's what I've discovered so far.

There is no real enforced concept of information hiding, no binding of
type to variable in fact no concept of typing at all as far as I can
see.

strong typing != static typing

Python is strongly typed, but not statically typed.
No interfaces and no subtype polymorphism (Python has 'Duck Type'
polymorphism and I haven't really explored all the ramifications of this
yet). It does however have multiple inheritance.
[snip]
Python doesn't have interfaces as in Java because it isn't statically
typed.

The idea behind Duck Typing is that the actual type doesn't matter; if
it supports the required method(s) and returns the expected type, then
that's good enough!

http://en.wikipedia.org/wiki/Duck_typing
 
M

Mark Lawrence

For what you're doing there, though, a class is overkill. Remember,
Python isn't Java; the most natural way to do everything isn't
necessarily to write a class that unpacks things and packs them up
again in a different way.

ChrisA

This shows just how poor the Python documentation is. I can't find the
"overcoming brainwashing" section anywhere!!!
 
M

Mark Lawrence

On 22/08/12 15:13, shaun wrote:

[snip]

Im very new to python and the object orientated feature doesnt seem
to be as well put together as Java. Can anyone help with this problem?

From one Java head to another I suggest you park what you know about
Java and approach Python with a clear mind.
[snip]

strong typing != static typing

Python is strongly typed, but not statically typed.
No interfaces and no subtype polymorphism (Python has 'Duck Type'
polymorphism and I haven't really explored all the ramifications of this
yet). It does however have multiple inheritance.

[snip]

The residents can be pretty defensive as well :)

Once again, no criticism intended.

lipska

I'm lost. I see nothing defensive at all. I see a statement of fact.
 
T

Terry Reedy

There is no real enforced concept of information hiding, no binding of
type to variable in fact no concept of typing at all as far as I can
see.

Given that type(valid_name) always returns a type(class), that is a
slightly strange statement. What is true is that there is no concept of
static type for names. In Python (and similar languages) type or class
is a property of objects, not names. This goes alone with names being
bound to objects rather than linear memory blocks. (Memory block is a
machine implementation of the abstraction 'information object'.) And
Python objects are more stfongly typed than in some other languages.
Names are only dynamically and indirectly typed when they are bound to
an object. Except for the few keyword names like None, True, etc, names
can be rebound to another object of another type.
 
I

Ian Kelly

In addition to the excellent feedback that Dave gave you:

def breakuparray(self):
for row in self.array:
mer = row[0].ljust(25, ' ')
merc = row[1].ljust(13, ' ')
mertype = row[2]
merloc = row[3]
mercount = row[4]
mersec = row[5]
acq = row[6]

This loops over each row in self.array and stores the contents in a
set of variables called mer, merc, etc. Note that as written these
variables are *local* to the breakuparray method, not attributes of
the class. Also note that on each iteration, you reassign to the same
variables again, wiping out all the work you did on the previous
iteration. In the end, only the last row is stored in the local
variables, and then even that is wiped out when the method returns.
def returnBatch(self):
self.breakuparray()
return "\x01001\x0251.%s%s%s%s%s%s%s%s\x03" % (mer, merc, mertype, merloc, mercount, mersec, acq);

This appears to be trying to use the same local variables from the
breakuparray method, but it can't. Those are out of scope here. If
you want to share these data between the breakuparray method and the
returnBatch method, you should either have breakuparray return them,
or you should store them as attributes on the object instance:
self.mer, self.merc, self.mertype, etc. (In Python, object attribute
storage is always explicit, never implicit as in Java and the rest of
the C++ family).
 
M

Mark Lawrence

On 22/08/12 16:58, MRAB wrote:
On 22/08/2012 15:59, lipska the kat wrote:
On 22/08/12 15:13, shaun wrote:

[snip]

Im very new to python and the object orientated feature doesnt seem
to be as well put together as Java. Can anyone help with this
problem?

The residents can be pretty defensive as well :)

Once again, no criticism intended.

lipska

I'm lost. I see nothing defensive at all. I see a statement of fact.


You seem to be perpetually lost Mark ...


lipska

Maybe but I seem to understand Python rather better than some people :)

Once again, no criticism intended.
 
I

Ian Kelly

If, in a language, I find I am able to say

a = 1

then later, in the same scope I can say

a = "foo"

then later again in the same scope I can say

a = ([1,2,3], "xyz", True)

then, and I may be missing something here, to me, that doesn't say 'strongly
typed' that says 'no typing constraints whatsoever'

You're conflating "strong typing" with "static typing". Strong typing
does not refer to restrictions on what type of data can be stored
where, but to restrictions on how operations on that data can be
intermixed.

The classic example of weak typing is concatenation of strings and
numbers, e.g. ("abc" + 123). Weakly typed languages like JavaScript
will implicitly coerce the number to a string and perform the
concatenation. Strongly typed languages like Python will raise a
TypeError instead.

Note that statically typed languages can be weakly typed as well. For
instance, C is commonly considered to be weakly typed because the
casting rules of that language allow you to treat any piece of data as
being of any type, even though the variables themselves are all
statically typed.
 
M

Mark Lawrence

Given that type(valid_name) always returns a type(class), that is a
slightly strange statement.

[snip]

Well I'm a beginner so I'm allowed to make strange statements.
However I don't think it's that strange and here's why.

If, in a language, I find I am able to say

a = 1

then later, in the same scope I can say

a = "foo"

then later again in the same scope I can say

a = ([1,2,3], "xyz", True)

then, and I may be missing something here, to me, that doesn't say
'strongly typed' that says 'no typing constraints whatsoever'

If you can show me a 'type' that cannot be assigned to

a

in the same scope then I would be most interested to know, I haven't
found one yet.

You've said nothing above except that any object you like can be bound
to a Python name. The name 'a' is never used. What happens when you
actually do something with the object that you've bound to 'a'?
We need to separate out the 'view' from the 'implementation' here.
Most developers I know, if looking at the code and without the possibly
dubious benefit of knowing that in Python 'everything is an object'
would not call this 'strong typing'

I really despair that after ten years of using Python people still seem
to be incapable of distinguishing strong, static, weak and dynamic
typing. Not that it's a specific Python problem of course, just that I
always get to read about it here.
Once again, this is not a criticism, it's an observation

It is OK to to make (possibly erroneous) observations isn't it?

Not if undoes concepts that computer scientists have patiently been
trying to explain for years.
 
E

Evan Driscoll

If you can show me a 'type' that cannot be assigned to

a

in the same scope then I would be most interested to know, I haven't
found one yet.

As other people have said, you've just pointed out the difference
between static typing and dynamic typing -- and how the former types
variables (or "names") and the latter types objects. I just have a few
things to add to your post and others.


First, from some point of view, you're correct. From a type theory point
of view "dynamically typed" is an oxymoron, because *by definition*
(from this point of view) types are a property of variables (and
expressions). For example, Ben Pierce says (in "Types and Programming
Languages"):

The word "static" is sometimes added explicitly...to distinguish
the sorts of compile-time analyses we are considering here from the
dynamic or latent typing found in languages such as Scheme, where
run-time type tags are used to distinguish different kinds of
structures in the heap. Terms like "dynamically typed" are arguably
misnomers and should probably be replaced by "dynamically checked,"
but the usage is standard.

(And the usage is standard because it's just really useful to be able to
say "dynamically-typed" instead of "uni-typed with runtime checks of
things that act like types". (I don't think Pierce's "dynamically
checked" is specific enough. :))


Second, this concept isn't *so* unfamiliar to you. If I give you the
following Java code:

void foo(Object o) { ... }

and ask what type 'o' is, there are kind of two answers. The first is
that 'o' is an 'Object'. But you can't make an Object -- that's an
abstract class. (IIRC. If it's not then just bear with me; you get the
idea. :)) So from a strictly static type-theory point of view, 'foo' is
unusable because it takes a type which you can never create. But of
course that's not the case, because in actual Java 'o' has some dynamic
type which is a subclass of 'Object'.

Though I'm sure this statement will be *really* popular with this list
</sarcasm>, if it puts your mind at ease a little, you can imagine that
there are no primitive types and Python names all have type 'Object',
but that you can refer to the functions in an object's dynamic type
without explicitly downcasting. (The analogy isn't perfect.)


The classic example of weak typing is concatenation of strings and
numbers, e.g. ("abc" + 123). Weakly typed languages like JavaScript
will implicitly coerce the number to a string and perform the
concatenation. Strongly typed languages like Python will raise a
TypeError instead.

I would also say don't get *too* caught up in categorizing everything
into "strong" and "weak"; that's a spectrum, and where things fall is a
lot more interesting than just "here or there". Really it's even more
complex than just a linear spectrum -- Language A can be stronger than
Language B in one respect but weaker in another.

In particular, it's possible to have rather stronger typing than Python
(especially with respect to Booleans, but in some other respects as well).

Evan


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEVAwUBUDUtCAOzoR8eZTzgAQI5fQf+JGJGss3/zHa80wTS64z5suZAzdPJ2DKx
o9OqXuA1Z+eL7xe4bztFVelEKM2cycAdZXuGX1oURzlK8TPWygCSm0a9PmS8zXxG
1LTCUCJSDon9iyUFmX3GJJf+bK3cQVXQj+ZYKHWxwI70AV6h9SgC4MFhamY0Itm/
NuUPn5cjiYh2j5C6klYYyQXFHIH2Eqh8PhRTrHnXQlhQmCQNvbMPvxNXB2Xo8sFT
mlPXCvl/jA1GxDhmdVCNjuwMqrsu3gqu6wHFdGPO89+JV9epwH+41tM1vo/a8IEf
UYuLtV/SwRori5ZiBkb/0SZhBrCJc7wAC6LxC3cl4VOefTTQE9PBRw==
=zsXj
-----END PGP SIGNATURE-----
 
M

MRAB

If you can show me a 'type' that cannot be assigned to

a

in the same scope then I would be most interested to know, I haven't
found one yet.
[snip]


Second, this concept isn't *so* unfamiliar to you. If I give you the
following Java code:

void foo(Object o) { ... }

and ask what type 'o' is, there are kind of two answers. The first is
that 'o' is an 'Object'. But you can't make an Object -- that's an
abstract class. (IIRC. If it's not then just bear with me; you get the
idea. :)) So from a strictly static type-theory point of view, 'foo' is
unusable because it takes a type which you can never create. But of
course that's not the case, because in actual Java 'o' has some dynamic
type which is a subclass of 'Object'.

Well I think this is where I'm struggling a bit.

looking at this method declaration I can see that the method takes an
argument of type Object (and just FYI class Object is not abstract and
you can do Object o = new Object()) and does not return a value.
I know that for the lifetime of this JVM, whatever o turns out to be it
will always be an Object. I can't assign a primitive to o as ints chars
floats etc are certainly not Objects. There are certain invariants that
give me a warm and comfortable feeling inside.

compare this to a function declaration in Python

def foo(self):
[snip]
That's not actually a declaration but a definition. :)

The function's body is bound to the name at runtime, so:

def double_it(x):
return x * 2

is not far from:

double_it = lambda x: x * 2

The only declarations are "global" and "nonlocal" (and the latter
exists only in recent versions of Python).
 
M

Mark Lawrence

compare this to a function declaration in Python

def foo(self):
[snip]
That's not actually a declaration but a definition. :)

The function's body is bound to the name at runtime, so:

def double_it(x):
return x * 2

is not far from:

double_it = lambda x: x * 2

The only declarations are "global" and "nonlocal" (and the latter
exists only in recent versions of Python).

Looking at the self I'm assuming that's a method and not a function.
 
E

Evan Driscoll

looking at this method declaration I can see that the method takes an
argument of type Object (and just FYI class Object is not abstract and
you can do Object o = new Object()) and does not return a value.
I know that for the lifetime of this JVM, whatever o turns out to be it
will always be an Object. I can't assign a primitive to o as ints chars
floats etc are certainly not Objects. There are certain invariants that
give me a warm and comfortable feeling inside.

I'm not saying it's nothing, but "can't assign a primitive" isn't much
of an invariant in the broad scheme of things when you can pass items as
diverse as lists, GUI buttons, files, etc. I would say it's more like if
you see 'int x' then *that* imposes a pretty big invariant, but passing
'Object' imposes almost nothing.

This is especially true considering the fact that you actually *can* say
'foo(4)' and Java will go and autobox the 4 into Integer(4) for you.

(BTW, this analogy suggests a way that's actually fairly useful for how
to look at Python coming from the Java perspective: Python just lacks
primitive types and things like integers are always boxed. Thus *all*
Python variables are essentially references.)

Evan


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEVAwUBUDVPnAOzoR8eZTzgAQK78Qf+LbGlDezuFJ/LwsmIlSuRi3ZwfqY8I/9j
wA3of5N8rmA3ETcJh+eNGuMLQ536SzDi3vlwSgMcKE1h97KmfV3F5PLkW9/v6OPC
dRqz4+8XsQjiCMm4PGMgbnxi1A0juYro9wNC4ltCs0cTNCK9wQyN54bDlS/RMMPn
fcSLzeK/rUsCUsgemVE9Qdkx50V4kguicAKt9bUS7jmzGEfVERd+3lffqn6fjdm0
W4rbxw1mUEnHYNDblJzY1uT86GU0n2yZZigsqkS2EhNxchh7CQXMgce9T2czIatT
jUdPEhU8kCats1QEPQkS20usonBj1UV1QjftYuGXNKp4TEn4S433UQ==
=7yUI
-----END PGP SIGNATURE-----
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top