所以在PHP中,我们通常通过构造函数传递依赖项。
喜欢
<?php
class Downloader
{
public function __construct(LoggerInterface $logger){}
}
但是在Python(我是初学者)中,我看到我们可以使用在类范围之外定义的对象可以直接使用。
logger = logging.getLogger('mylogger')
class Downloader():
def download():
logger.alert('I am downloading..')
我想了解python开发人员如何在类中使用服务的建议。
答案 0 :(得分:1)
我不会依赖它在全球范围内,我要么让它成为班级成员
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..')
答案 1 :(得分:1)
嗯,这取决于。如果某些东西不会被改变并且对于文件或模块中的所有类都是通用的,那么我倾向于直接使用它而不通过构造函数传递它,否则,我在类级别定义一个变量,如果我想在继承的类中修改它。
在您的情况下,如果下载程序类(以及从中继承的所有人)总是要使用同一个记录器,那么我认为使用它的方式没有任何问题。/ p>
# 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')
答案 2 :(得分:1)
就我而言,我只喜欢在类本身中实例化依赖项
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)