gpt4 book ai didi

Python打印对象设计

转载 作者:行者123 更新时间:2023-11-30 23:04:51 26 4
gpt4 key购买 nike

在以下类中,每个对象都有自己的(自定义)打印函数,称为pprint

(实际代码中的对象比下面显示的要多)。

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):

在以下选项中,哪个更好/更高效/更Pythonic?

  • 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 函数:导入打印机p = 打印机()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)
    • 缺点:代码缺乏组织性并且有点困惑。

最佳答案

我建议您将 __str__ 方法添加到每个类定义中,然后使用标准内置函数进行打印:print(class_instance)。在内部,python 调用 __str__ 来获取实例的字符串表示形式。

关于Python打印对象设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33506358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com