Python 以优雅的方式初始化许多对象
我正在寻找一种优雅的方法来初始化许多对象 假设我有一个Python 以优雅的方式初始化许多对象,python,python-3.x,Python,Python 3.x,我正在寻找一种优雅的方法来初始化许多对象 假设我有一个Utils模块,它有一个到SVN、Git、Make和其他东西的接口 目前,我是这样做的: from Utils.Config import Config, Properties from Utils.Utils import PrettyPrint, SVN, Make, Bash, Git class Build(object): def __init__(self): self.config = Config(
Utils
模块,它有一个到SVN、Git、Make和其他东西的接口
目前,我是这样做的:
from Utils.Config import Config, Properties
from Utils.Utils import PrettyPrint, SVN, Make, Bash, Git
class Build(object):
def __init__(self):
self.config = Config()
self.make = Make()
self.env = Properties()
self.svn = SVN()
self.git = Git()
self.bash = Bash()
self.pretty_print = PrettyPrint()
from collections import UserString, deque, UserDict
def construct(instance, classes = (UserString, deque, UserDict)):
for c in classes:
setattr(instance, c.__name__.lower(), c([]))
和。。嗯,看起来不太好
有没有更优雅的方法?我想这可能是一个设计问题,但我不知道如何解决这个问题
我正在考虑创建
基类
,它将在Utils
模块中初始化所有这些类。你觉得怎么样?我不会创建一个类并将其作为一个基础,这似乎有些过分,过于庞大
相反,您可以创建一个辅助的helper函数,它接受self
和setattr
。其中的一个示例包含来自的两个对象,如下所示:
from Utils.Config import Config, Properties
from Utils.Utils import PrettyPrint, SVN, Make, Bash, Git
class Build(object):
def __init__(self):
self.config = Config()
self.make = Make()
self.env = Properties()
self.svn = SVN()
self.git = Git()
self.bash = Bash()
self.pretty_print = PrettyPrint()
from collections import UserString, deque, UserDict
def construct(instance, classes = (UserString, deque, UserDict)):
for c in classes:
setattr(instance, c.__name__.lower(), c([]))
您的案例也非常适合,因为您的对象没有所需的初始值,所以您可以用相同的方式概括和处理它们:-)
现在,您的示例类只需调用construct()
,使用\uuuu init\uuuu
中的默认值,即可完成以下操作:
class Foo:
def __init__(self):
construct(self)
当然,可以根据需要在
Utils
中定义construct
函数,或者将其定义为类中的方法 您可以执行constructors={'config':config,'make':make,…}
然后迭代constructors
实例化类和setattr
类上的值,但是您实际上没有获得太多(如果有的话)。真正的问题是,你不得不说,你想在属性名Y中放一个X的实例——而且似乎没有足够的押韵/理由来真正减少键入(这本身并不是一件坏事)。对我来说,我看到的一个危险信号是,这个类同时拥有self.svn和self.git,为什么同一个类同时拥有这两个呢?对我来说,我看到的一个危险信号是,这个类同时拥有self.svn和self.git,为什么同一个类同时拥有这两个呢?我的公司在svn有一条腿,在git有一条腿。这个程序需要SVN和Git的依赖关系。我也不喜欢这个。谢谢你的评论!这个utils类似乎是一个非常糟糕的代码味道。它捆绑不相关的对象,不必要地组合这些API,与构造函数中的类紧密耦合。。。