在以下类中,每个对象都有自己的(自定义)打印函数,称为pprint。Python打印对象设计
(实际代码中有更多的对象比下面介绍的更多)。
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):
在下列选项中,什么是更好/更高效/更Python?
1.将一个pprint函数每类中(如上面):
- 优势:
obj.pprint(args)
是易于使用。 - 缺点:每对象我想打印有它自己的pprint函数,所以它会降低代码的可读性,以确保课程真正重要。
- 优势:
2.有一个专门的打印机类:
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):
注: pprint将调用基于对象的类型选择合适的打印功能。
- 优势:代码是更有条理。
- 缺点:必须导入类,创建一个打印机对象,每次调用它来获得pprint功能:
import Printer
p = Printer()
p.pprint(obj)
3.有没有专用的打印机类:
def pprint(obj, disp=MORE, keyList=None, filters=[], padding=20): def devicePrint(obj, disp=MORE): def interfacePrint(obj, disp=MORE):
注意: pprint将根据对象的类型调用适当的打印功能。
- 优势:不必实例化任何打印机对象。可以直接致电
pprint(obj)
查询任何对象。 - 缺点:代码少组织和一种混乱。
- 优势:不必实例化任何打印机对象。可以直接致电
我通常实现'__repr__'或'__str__'方法。然后我可以使用标准的“打印”或“记录”功能。似乎更多Pythonic给我。我想这很像你的选择1.选项2和3意味着Printer类必须详细了解其他类的实现,这似乎违反了基本的面向对象原则。但这更像是一个意见问题,这在SO中通常是不被接受的。 – RobertB