gpt4 book ai didi

python将函数传递给类

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:05 24 4
gpt4 key购买 nike

我正在编写简单的基于 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/

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