假设我使用的库实现了一个类
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):
...
是否可以在不调用私有API的情况下初始化Derived
?
换句话说,我应该替换factory
函数?
答案 0 :(得分:0)
如果您无权访问私有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()