所以在PHP中,我们通常通过构造函数传递依赖项。你知道吗
就像
<?php
class Downloader
{
public function __construct(LoggerInterface $logger){}
}
但是在Python中(我是初学者),我看到我们可以使用在类范围之外定义的对象来直接使用。你知道吗
logger = logging.getLogger('mylogger')
class Downloader():
def download():
logger.alert('I am downloading..')
我想了解python开发人员如何在类内使用服务的建议。你知道吗
在我的例子中,我只喜欢在类本身中引用依赖项
另一种选择是在类创建时将依赖项作为参数传递
我不指望它在全局范围内,我要么让它成为类级别的成员
或实例级成员
那要看情况了。如果文件或模块中的所有类都有一个不需要改变的通用类,那么我倾向于直接使用它,而不通过构造函数传递它,或者,如果我想在继承类中修改它,我在类级别定义一个变量。你知道吗
在您的例子中,如果downloader类(以及从它继承的所有类)总是要使用同一个记录器,那么我认为以您现在的方式使用它没有问题。你知道吗
相关问题 更多 >
编程相关推荐