我可以从只能由“工厂"创建的类派生吗? [英] Can I derive from a class that can only be created by a "factory"?
本文介绍了我可以从只能由“工厂"创建的类派生吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我使用的库实现了一个类
Suppose that a library I'm using implements a class
class Base(object):
def __init__(self, private_API_args):
...
它只能通过实例化
def factory(public_API_args):
"""
Returns a Base object
"""
...
我想通过添加几个方法来扩展 Base
类:
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):
...
是否可以在不调用私有 API 的情况下初始化 Derived
?
Is it possible to initialize Derived
without calling the private API though?
换句话说,我应该用什么替代 factory
函数?
In other words, what should be my replacement for the factory
function?
推荐答案
如果您没有任何访问私有 API 的权限,您可以执行以下操作:
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):
...
现在在主脚本中:
#!/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()
这篇关于我可以从只能由“工厂"创建的类派生吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文