python将函数传递给类

标签 python

我正在编写简单的基于 telnetlib 的库,供其他 python 脚本使用。我也在使用日志记录类,因此我有一个问题:是否有可能,做这样的事情是否是一种很好的 python 实践:

def printd(args):
    """ debug on stdout """
    sys.stdout.write(time.strftime("%H:%M:%S ") + args.rstrip() + '\n')

def printe(args):
    """ error on stderr """
    sys.stderr.write(time.strftime("%H:%M:%S ") + args.rstrip() + '\n')


class Connections:
    """ Telnet lib connection wrapper """

    def __init__(self, host, port, timeout, logger):
        """ if external logger is passed -  all msgs will be passed to it,
        otherwise will use printd and printe functions """

        self.timeout = timeout
        self.host = host
        self.port = port
        self.connections = {}

        try:
            res = isinstance(logger, logging.Logger)
        except TypeError:
            res = False
        except:
            res = False

        if res == True:
            self.log = logger
            self.log_debug = self.log.debug
            self.log_info = self.log.info
            self.log_error = self.log.error
        else:
            self.log_debug = printd
            self.log_error = printe

    def connect2(self, helloMsg):
        try:
            self.c = telnetlib.Telnet(self.host, self.port)
        except socekt.error:
            self.c = None
            self.log_error("Could not connect to %s:%d" % (self.host, self.port))
        except IOError:
            self.log_error("Could not connect to %s:%d" % (self.host, self.port))
            self.c = None

在构造函数中我传递了记录器,如果它存在,我想使用它的日志方法来打印消息,如果不存在,我想使用 printdprinte 函数.

最佳答案

是的,这在原则上完全没问题,除了 isinstance(logger, logging.Logger) 永远不会引发 TypeError。它只会返回一个 bool 值。写起来更容易也更 pythonic

def __init__(self, host, port, timeout, logger=None):
    if logger is None:
        self.log_debug = printd
        self.log_error = printe
    else:
        # use the logger's methods

然后你可以传递None来获取内置的日志记录。

关于python将函数传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13882361/

相关文章:

python - 如何从列中选择所有元素,它是python中DataFrame中的列表?

python - 图例中的颜色与图表颜色不匹配

python - 为什么我的 .fetchone 函数返回 "none"?

python - 我如何在 jinja2 中构建可重用的小部件?

python - 使用 Scapy 提取 TCP 数据

python - CS50 DNA 适用于小型 .csv 但不适用于大型

python - Matplotlib PDF 后端慢?

python - 叠加图像并在每个像素位置显示较亮的像素

python - 将多核与 LocalMRJobRunner 用于 MRJob

python - 如何控制 tensorflow 中的维度广播?