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

.



Relevant Pages

  • Re: Moving from java to python.
    ... I have recently been learning python, ... [uid - an identifier for comparisons.] ... for i in connections: ... def getConnected: ...
    (comp.lang.python)
  • Re: threads and memory
    ... connections to a remote service in order to "stress test" that the remote ... service can handle that many connections. ... I am running into a problem where asyncore is through a filedescriptor error if I try to launch more that 1023 connections: ... def handle_connect: ...
    (comp.lang.python)
  • Re: Moving from java to python.
    ... I have recently been learning python, ... [uid - an identifier for comparisons.] ... for i in connections: ... def getConnected: ...
    (comp.lang.python)
  • Re: Moving from java to python.
    ... for node, weight in connections: ... Also note that Python doesn't really use the camel-case naming ... Why not simply def connectionsor, if you must, def ...
    (comp.lang.python)
  • Re: Moving from java to python.
    ... > for i in connections: ... > if not uid: ... the need for anything other than the idis suspect. ... > def getConnected: ...
    (comp.lang.python)