On the following classes, each object has it's own (customized) print function called pprint.
(There is more objects in the actual code than what's presented below).
class Device(object):
"""
Device: a MAC address, a name (optional), an ip(s) (optional),
and a list of Interface objects.
"""
def __init__(self, ip='', name='', mac=''):
def addIp(self, ip):
def getInterface(self, name):
def removeDuplicates(self):
def pprint(self, disp=MORE):
def toCSV(self, outputFolder=outputPath):
class Interface(object):
"""
Interface: a name, a status and a set of Link objects.
It can be physical (port) or virtual (interface).
e.g: name : BAGG1,
status: TRUNK,
links : [(vlan1, mac1), (vlan2, mac2), ...]
"""
def __init__(self, name):
self.name = name
self.links = []
self.status = ''
def addLink(self, vlan='', destMAC=''):
def getValues(self):
def _removeDuplicates(self):
def pprint(self, disp=MORE):
Among the following options, what is better/more efficient/more Pythonic ?
1. Put a pprint function inside each class (like above):
- Advantage:
obj.pprint(args)is easy to use. - Disadvantage: every object I want to print has its own pprint function, so it decreases code readability for what really matters in the class.
- Advantage:
2. Have a dedicated Printer class:
class NetworkPrinter(object): def __init__(self, obj): def pprint(self, disp=MORE, keyList=None, filters=[], padding=20): def devicePrint(self, disp=MORE): def interfacePrint(self, disp=MORE):Note: pprint will call the appropriate print function based on the type of the object.
- Advantage: Code is more organized.
- Disadvantage: Have to import the class, create a printer object and call it each time to get the pprint function:
import Printerp = Printer()p.pprint(obj)
3. Have no dedicated Printer class:
def pprint(obj, disp=MORE, keyList=None, filters=[], padding=20): def devicePrint(obj, disp=MORE): def interfacePrint(obj, disp=MORE):Note: pprint will call the appropriate print function based on the type of the object.
- Advantage: Don't have to instantiate any Printer object. Can call directly
pprint(obj)for any object. - Disadvantage: Code less organized and kind of messy.
- Advantage: Don't have to instantiate any Printer object. Can call directly
__repr__or a__str__method. Then I can use standard "print" or "logging" functions. Seems more Pythonic to me. I guess this is most like your option 1. Option 2 and 3 mean that the Printer class has to have detailed knowledge of the implementation of the other classes, which seems like a violation of basic object oriented principles. But this is more of an opinion question which is typically frowned upon at SO.