473,223 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,223 software developers and data experts.

Moving from java to python.

Hi,

I have recently been learning python, and coming from a java
background there are many new ways of doing things that I am only just
getting to grips with.

I wondered if anyone could take a look at a few pieces of code I have
written to see if there are any places where I am still using java-
esque techniques, and letting me know the appropriate python way of
doing things.
Here is a node class I wrote for use in graph traversal algorithms:

#====

class Node:
"""
Node models a single piece of connected data.

Author: Peter Braden
Last Modified : Nov. '07
"""

def __init__(self, connections = None, uid = None):
"""
Args:
[connections - a list of (connected node, weight) tuples. ]
[uid - an identifier for comparisons.]
"""
self._connected = []
self._weights = []

if connections:
for i in connections:
self.connected.append(i[0])
self.weights.append(i[1])

if not uid:
self.id = id(self)
else:
self.id = uid

def __eq__(self, other):
return self.id == other.id

def getConnected(self):
return self._connected

def getWeights(self):
return self._weights

def getConnections(self):
connections = []
for i in range(len(connected)):
connections.append((self._connected[i],self._weight[i]))
return connections

connected = property(getConnected, None)
weights = property (getWeights, None)
connections = property(getConnections, None)

def addConnection(self, node, weight = 0):
self.connected.append(node)
self.weights.append(weight)

def removeConnection(self, node):
i = self._connected.index(node)
del self._connected[i]
del self._weights[i]

#===

Cheers,
Peter

Nov 12 '07 #1
5 1427
Pe**********@googlemail.com napisał(a):
def getConnected(self):
return self._connected
No need to use accessors. Just plain attribute lookup is sufficient.

--
Jarek Zgoda
Skype: jzgoda | GTalk: zg***@jabber.aster.pl | voice: +48228430101

"We read Knuth so you don't have to." (Tim Peters)
Nov 12 '07 #2
On Nov 12, 3:25 pm, "PeterBrad...@googlemail.com"
<PeterBrad...@googlemail.comwrote:
Hi,

I have recently been learning python, and coming from a java
background there are many new ways of doing things that I am only just
getting to grips with.

I wondered if anyone could take a look at a few pieces of code I have
written to see if there are any places where I am still using java-
esque techniques, and letting me know the appropriate python way of
doing things.

Here is a node class I wrote for use in graph traversal algorithms:

#====

class Node:
"""
Node models a single piece of connected data.

Author: Peter Braden
Last Modified : Nov. '07
"""

def __init__(self, connections = None, uid = None):
"""
Args:
[connections - a list of (connected node, weight) tuples. ]
[uid - an identifier for comparisons.]
"""
self._connected = []
self._weights = []

if connections:
for i in connections:
self.connected.append(i[0])
self.weights.append(i[1])

if not uid:
self.id = id(self)
else:
self.id = uid

def __eq__(self, other):
return self.id == other.id

def getConnected(self):
return self._connected

def getWeights(self):
return self._weights

def getConnections(self):
connections = []
for i in range(len(connected)):
connections.append((self._connected[i],self._weight[i]))
return connections

connected = property(getConnected, None)
weights = property (getWeights, None)
connections = property(getConnections, None)

def addConnection(self, node, weight = 0):
self.connected.append(node)
self.weights.append(weight)

def removeConnection(self, node):
i = self._connected.index(node)
del self._connected[i]
del self._weights[i]
There's no reason to make 'connected' and 'weights' properties: just
use them directly.

Make 'connections' default to [] rather than None, and replace the
slightly clumsy initialisation with more direct code:

self.connected = [i[0] for i in connections]
self.weights = [i[1] for i in connections]

getConnections can be much simpler...

def getConnections(self):
return zip(self.connected, self.weights)

The 'uid' business makes me suspicious: what's it for? If you need it,
you probably need to initialise with an explicit test for None rather
than just 'if uid' which will be wrong if you use a uid of 0...

self.id = uid if uid is not None else id(self)

HTH
--
Paul Hankin

Nov 12 '07 #3
"Pe**********@googlemail.com" <Pe**********@googlemail.comwrites:
def __init__(self, connections = None, uid = None):
You can use connections=(), so you don't need the "if" below. In
fact, you can further write:

for node, weight in connections:
self._connected.append(node)
self._weight.append(weight)
def getConnected(self):
return self._connected
I'd drop the getters and simply use self.connected, self.weights, etc.
It's not such a big deal in Python if someone can view the innards of
your objects; they can do so even if their name starts with _.

Also note that Python doesn't really use the camel-case naming
convention. If you must have multi-word method/variable/property
names, use lower-case with underscores for separation. For example:
def getConnections(self):
Why not simply def connections(self) or, if you must, def
get_connections(self).
connections = []
for i in range(len(connected)):
connections.append((self._connected[i],self._weight[i]))
Use xrange(len(...)) when iterating over the sequence; range
unnecessarily allocates the whole list. Some will probably recommend
enumerate() or even itertools.izip(), but those are overkill for this
usage.
Nov 12 '07 #4
def __init__(self, connections = None, uid = None):
"""
Args:
[connections - a list of (connected node, weight) tuples. ]
[uid - an identifier for comparisons.]
"""
self._connected = []
self._weights = []

if connections:
for i in connections:
self.connected.append(i[0])
self.weights.append(i[1])
I'd likely write this something like

if connections:
self.connected, self.weights = zip(*connections)

You also shift here between "_connected" and "connected" (same
with weights). This might bite you.
if not uid:
self.id = id(self)
else:
self.id = uid
A common way of writing this would be

self.id = uid or id(self)

However, the need for anything other than the id() is suspect.
Imaginable, but suspect.
def getConnected(self):
return self._connected

def getWeights(self):
return self._weights
connected = property(getConnected, None)
weights = property (getWeights, None)
No need for properties at this time...they can be added
transparently later, if you need to do something programatic on
access.
def getConnections(self):
connections = []
for i in range(len(connected)):
connections.append((self._connected[i],self._weight[i]))
return connections

connections = property(getConnections, None)
And in an inverse of the __init__ method, I'd use something like

def getConnections(self):
return zip(self.connected, self.weights)

Just my first-pass thoughts...

-tkc


Nov 12 '07 #5
Paul Hankin wrote:
On Nov 12, 3:25 pm, "PeterBrad...@googlemail.com"
<PeterBrad...@googlemail.comwrote:
>Hi,

I have recently been learning python, and coming from a java
background there are many new ways of doing things that I am only just
getting to grips with.

I wondered if anyone could take a look at a few pieces of code I have
written to see if there are any places where I am still using java-
esque techniques, and letting me know the appropriate python way of
doing things.

Here is a node class I wrote for use in graph traversal algorithms:

#====

class Node:
"""
Node models a single piece of connected data.

Author: Peter Braden
Last Modified : Nov. '07
"""

def __init__(self, connections = None, uid = None):
"""
Args:
[connections - a list of (connected node, weight) tuples. ]
[uid - an identifier for comparisons.]
"""
self._connected = []
self._weights = []

if connections:
for i in connections:
self.connected.append(i[0])
self.weights.append(i[1])

if not uid:
self.id = id(self)
else:
self.id = uid

def __eq__(self, other):
return self.id == other.id

def getConnected(self):
return self._connected

def getWeights(self):
return self._weights

def getConnections(self):
connections = []
for i in range(len(connected)):
connections.append((self._connected[i],self._weight[i]))
return connections

connected = property(getConnected, None)
weights = property (getWeights, None)
connections = property(getConnections, None)

def addConnection(self, node, weight = 0):
self.connected.append(node)
self.weights.append(weight)

def removeConnection(self, node):
i = self._connected.index(node)
del self._connected[i]
del self._weights[i]

There's no reason to make 'connected' and 'weights' properties: just
use them directly.

Make 'connections' default to [] rather than None, and replace the
slightly clumsy initialisation with more direct code:

self.connected = [i[0] for i in connections]
self.weights = [i[1] for i in connections]

getConnections can be much simpler...

def getConnections(self):
return zip(self.connected, self.weights)

The 'uid' business makes me suspicious: what's it for? If you need it,
you probably need to initialise with an explicit test for None rather
than just 'if uid' which will be wrong if you use a uid of 0...

self.id = uid if uid is not None else id(self)

HTH
--
Paul Hankin
Be VERY careful with using [] as default arguments. Mutables are only evaluated
once (not at every call). This question comes up about once a week on this
forum where people don't understand this.

I would recommend using (if you can):

def __init__(self, connected = None, weights=None, uid = None):
self.connected = connected or []
self.weights = weights or []
If you want to stay with single connections list do this:

def __init__(self, connections = None, uid = None):
if connections is not None:
self.connected=[c[0] for c in connections]
self.weights=[c(1) for c in connections]

else:
self.connected=[]
self.weights=[]

Others have addressed the lack of need for accessors.

-Larry
Nov 12 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Dave Brueck | last post by:
Below is some information I collected from a *small* project in which I wrote a Python version of a Java application. I share this info only as a data point (rather than trying to say this data...
1
by: bezeee | last post by:
At my work we are in the process of building a tool to test an XML based API. Basically, XML in and XML out over http. Currently, there are two engines that do all of the schema validations, xml...
1
by: greg.knaddison | last post by:
Hi, I'm trying to use the httpclient within Jython (see http://jakarta.apache.org/commons/httpclient/ for more information on the httpclient). My Jython version is: Jython 2.1 on...
14
by: Wolfgang Keller | last post by:
Hello, as a non-developer I am currently participating in an industrial "research" project to develop a so-called "web application". This application serves at the same time as middleware to...
4
by: angel | last post by:
A java runtime environment includes jvm and java class (for example classes.zip in sun jre). Of course jython need jvm,but does it need java class. Thanx
9
by: F. GEIGER | last post by:
I've dev'ed a Python prototype of an app, that besides the internals making it up has a gui. While test-driven dev'ing the app's internals in Python is fun as usual, dev'ing the GUI is not so...
114
by: Maurice LING | last post by:
This may be a dumb thing to ask, but besides the penalty for dynamic typing, is there any other real reasons that Python is slower than Java? maurice
18
by: steve.anon | last post by:
Hi I'm a Java developer moving to windows only applications. Of course the first thing I thought was "well at least, without the VM now I can write desktop applications that run real fast". So I...
12
by: Mark Fink | last post by:
I wrote a Jython class that inherits from a Java class and (thats the plan) overrides one method. Everything should stay the same. If I run this nothing happens whereas if I run the Java class it...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.