编程语言
首页 > 编程语言> > Python:我应该在这里使用委托还是继承?

Python:我应该在这里使用委托还是继承?

作者:互联网

我在思考是否应该使用继承或委托来实现一种包装类.我的问题是这样的:假设我有一个名为Python的类.

class Python:

    def __init__(self):
        ...

    def snake(self):
        """ Make python snake through the forest"""
        ...

    def sleep(self):
        """ Let python sleep """
        ...

……还有更多的行为.现在我有一些代码需要一个Anaconda,它几乎就像一个Python,但略有不同:一些成员的名称和参数略有不同,其他成员添加了新的功能.我真的想在Python中重用代码.因此我可以通过继承来做到这一点:

class Anaconda(Python):

    def __init__(self):
        Python.__init__(self)

    def wriggle(self):
        """Different name, same thing"""
        Python.snake(self)

    def devourCrocodile(self, croc):
        """ Python can't do this"""
        ...

当然我也可以打电话给Anaconda().sleep().但问题是:我需要使用PythonFactory.

class PythonFactory:

    def makeSpecialPython(self):
        """ Do a lot of complicated work to produce a special python"""
        …
        return python

我想要它制作一个Python,然后我应该能够将它转换为Anaconda:

myAnaconda = Anaconda(PythonFactory().makeSpecialPython())

在这种情况下,授权将是一条路. (我不知道是否可以使用继承来完成):

class Anaconda:

    def __init__(self, python):
        self.python = python

    def wriggle(self):
        self.python.wriggle()


    def devourCrocodile(self, croc):
        ...

但是有了代表团,我不能打电话给Anaconda().sleep().

所以,如果你还在我身边,我的问题是:

A)在类似的情况下,我需要

>添加一些功能
>重命名一些功能
>否则使用“基类”功能
>将“基类”对象转换为“子类”对象

我应该使用继承还是委托? (或者是其他东西?)

B)一个优雅的解决方案是使用委托加上一些特殊的方法来转发Anaconda不响应其Python实例的所有属性和方法访问.

解决方法:

B) An elegant solution would be to use delegation plus some special method that forwards all attribute and method accesses which Anaconda does not respond to to its instance of Python.

这在Python中很简单,只需定义__getattr__:

class Anaconda:

    def __init__(self, python):
        self.python = python

    def wriggle(self):
        self.python.snake()


    def devourCrocodile(self, croc):
        ...

    def __getattr__(self, name):
        return getattr(self.python, name)

请参阅__getattr__上的Python文档

标签:python,oop,python-3-x,inheritance,delegation
来源: https://codeday.me/bug/20190613/1233185.html