我可以从一个只能由 "工厂 "创建的类中派生吗?[英] Can I derive from a class that can only be created by a "factory"?

本文是小编为大家收集整理的关于我可以从一个只能由 "工厂 "创建的类中派生吗?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

假设我正在使用的库会实现类

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

它只能通过

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

我想通过向其添加几种方法来扩展Base类:

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

可以初始化Derived而无需调用私有API吗?

换句话说,我应该替换factory函数?

推荐答案

如果您无法访问私有API,则可以执行以下操作:

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):
        ...

现在在主要脚本中:

#!/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://www.itbaoku.cn/post/1937864.html

问题描述

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?

推荐答案

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()