问题
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