私は基本クラスのコンストラクターをファクトリとして使用しており、このコンストラクター/ファクトリのクラスを変更して適切なクラスを選択しています-このアプローチはPythonの優れた実践ですか、それともより洗練された方法がありますか?
メタクラスに関するヘルプを読み込もうとしましたが、大きな成功はありませんでした。
これが私がしていることの例です。
class Project(object):
"Base class and factory."
def __init__(self, url):
if is_url_local(url):
self.__class__ = ProjectLocal
else:
self.__class__ = ProjectRemote
self.url = url
class ProjectLocal(Project):
def do_something(self):
# do the stuff locally in the dir pointed by self.url
class ProjectRemote(Project):
def do_something(self):
# do the stuff communicating with remote server pointed by self.url
このコードがあれば、基本クラスProjectを介してProjectLocal/ProjectRemoteのインスタンスを作成できます。
project = Project('http://example.com')
project.do_something()
別の方法は、URLに基づいてクラスオブジェクトを返すファブリック関数を使用することです。コードは次のようになります。
def project_factory(url):
if is_url_local(url):
return ProjectLocal(url)
else:
return ProjectRemote(url)
project = project_factory(url)
project.do_something()
私の最初のアプローチは好みの問題ですか、それともいくつかの隠れた落とし穴がありますか?