Python管理依赖关系的方法

2024-09-29 19:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

所以在PHP中,我们通常通过构造函数传递依赖项。你知道吗

就像

<?php

class Downloader
{
    public function __construct(LoggerInterface $logger){}

}

但是在Python中(我是初学者),我看到我们可以使用在类范围之外定义的对象来直接使用。你知道吗

logger = logging.getLogger('mylogger')

class Downloader():
    def download():
        logger.alert('I am downloading..')

我想了解python开发人员如何在类内使用服务的建议。你知道吗


Tags: 对象定义loggingfunctiondownloaderpublicloggerconstruct
3条回答

在我的例子中,我只喜欢在类本身中引用依赖项

class Downloader():
    logger = logging.getLogger('mylogger')
    def download():
        logger.alert('I am downloading..')

另一种选择是在类创建时将依赖项作为参数传递

logger = logging.getLogger('mylogger')

class Downloader():
    def __init__(self, logger):
        self.logger = logger
    def download():
        logger.alert('I am downloading..')

downloader = Download(logger)

我不指望它在全局范围内,我要么让它成为类级别的成员

class Downloader():
    logger = logging.getLogger('mylogger')

    def download(self):
        logger.alert('I am downloading..')

或实例级成员

class Downloader():
    def __init__(self):
        self.logger = logging.getLogger('mylogger')

    def download(self):
        self.logger.alert('I am downloading..')

那要看情况了。如果文件或模块中的所有类都有一个不需要改变的通用类,那么我倾向于直接使用它,而不通过构造函数传递它,或者,如果我想在继承类中修改它,我在类级别定义一个变量。你知道吗

在您的例子中,如果downloader类(以及从它继承的所有类)总是要使用同一个记录器,那么我认为以您现在的方式使用它没有问题。你知道吗

# Case 1
# In case you want to allow logger being different for inherited classes.

class BaseDownloader(object):

      logger = Logger1

class Downloader1(BaseDownloader):

      logger = Logger2

# Case 2
# In case you want different logger for every instance

class Downloader(object):

      def __init__(self, logger):
           self.logger = logger

# Case 3
# If you don't need that kind of customizability, then using it directly
# is perfectly fine. In fact, that's how I'd start with, and change it
# later if the need arises.

class Downloader(object):

      def download():
          logger.alert('I am downloading')

相关问题 更多 >

    热门问题