我正在PyQt中设计一个使用特定网站帐户的应用程序。所以我有一个名为Account的基类,以及从帐户派生的网站特定帐户类,例如:GoogleAccount,YouTubeAccount等。
这些派生的Account类中的每一个都需要描述它是否具有下载,上载或两者的功能。基本上是否为特定网站实现了下载或上传接口方法。因此,特定网站的每个帐户实例都具有相同的下载/上传功能。
我正在试图弄清楚如何构建这些可以具有可下载/可上载功能的特定组合的Account类。我提出的一个解决方案是使用Interface Segregration Principle中的多继承类型模式:
class Downloadable(metaclass=ABCMeta):
@abstractmethod
def doDownload(): raise NotImplementedError("Reimplement me")
class Uploadable(metaclass=ABCMeta):
@abstractmethod
def doUpload(): raise NotImplementedError("Reimplement me")
class YoutubeAccount(Account, Downloadable):
""" All accounts from this website implement download capability """
def doDownload(): # dostuff
def otherMethods(): pass
class GoogleAccount(Account, Downloadable, Uploadable):
""" All accounts on this website implement both download and upload capability """
def doDownload(): # doStuff
def doUpload(): # doStuff
def otherMethods(): pass
另一个超级简单的解决方案是添加两个布尔类属性
class YoutubeAccount(Account):
DOWNLOADABLE = True
UPLOADABLE = False
def doDownload(): # doStuff
class GoogleAccount(Account):
DOWNLOADABLE = True
UPLOADABLE = True
def doDownload(): # doStuff
def doUpload(): # doStuff
要检查下载/上传功能(例如,要显示所有可下载的帐户),您可以使用isinstance(account, Downloadable)
作为第一个多重继承解决方案,使用account.DOWNLOADABLE
作为第二个布尔解决方案
我倾向于第一个具有多重继承的解决方案。还有其他人对如何构建这样的类有任何其他建议吗?
答案 0 :(得分:0)
如果你只有少数来自ERROR! The server quit without updating PID file (/usr/local/mysql/data/xxx.pid)
的类,我认为python方式是选项2。
但如果它违反了您关注的DRY原则(因为这些类属性可以从相应的方法派生),您可以在Account
基类上添加canDownload
和canUpload
方法并让他们分别返回Account
和hasattr(self, "doDownload")
。