gpt4 book ai didi

Python 管理依赖关系的方法

转载 作者:行者123 更新时间:2023-11-30 22:27:06 24 4
gpt4 key购买 nike

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

喜欢

<?php

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

}

但是在Python(我是初学者)中,我发现我们可以使用类范围之外定义的对象,可以直接使用。

logger = logging.getLogger('mylogger')

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

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

最佳答案

嗯,这要看情况。如果有一些东西不会被改变并且对于文件或模块中的所有类都是通用的,那么我倾向于直接使用它而不通过构造函数传递它,否则,我在类级别定义一个变量,如果我想在继承的类中修改它。

就您而言,如果下载器类(以及所有继承它的类)始终要使用同一个记录器,那么我认为按照您现在的方式使用它没有问题。

# 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')

关于Python 管理依赖关系的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038399/

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