问题描述
假设我正在使用的库会实现类
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()
问题描述
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()