Can I derive from a class that can only be created by a “factory”?

回眸只為那壹抹淺笑 提交于 2019-12-12 03:42:57

问题


Suppose that a library I'm using implements a class

class Base(object):
    def __init__(self, private_API_args):
        ...

It's meant to be instantiated only via

def factory(public_API_args):
    """
    Returns a Base object
    """
    ...

I'd like to extend the Base class by adding a couple of methods to it:

class Derived(Base):
    def foo(self):
        ...
    def bar(self):
        ...

Is it possible to initialize Derived without calling the private API though?

In other words, what should be my replacement for the factory function?


回答1:


If you do not have any access to the private API, you can do the following thing:

class Base(object):
    def __init__(self, private_API_args):
        ...


def factory(public_API_args):
    """ Returns a Base object """
    # Create base object with all private API methods
    return base_object


class Derived(object):
    def __init__(self, public_API_args):
        # Get indirect access to private API method of the Base object class
        self.base_object = factory(public_API_args)

    def foo(self):
        ...
    def bar(self):
        ...

And now in the main script:

#!/usr/bin/python3

# create the derivate object with public API args
derived_object = Derived(public_API_args)

# to call private API methods
derived_object.base_object.method()

# to call your method from the same object
derived_object.foo()
derived_object.bar()


来源:https://stackoverflow.com/questions/38836510/can-i-derive-from-a-class-that-can-only-be-created-by-a-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!