Reputation: 537
I have a strange case where I have to inherit from a class that is defined later in my python file, like the following:
class Client(BaseClient):
def __init__(self, url):
super().__init__(url)
...
...
class BaseClient:
def __init__(self, url):
...
I cannot do that because BaseClient
is not defined when I inherit from it. Is there a way to prototype the base class in the beginning of my code so it works? Or maybe another workaround?
Upvotes: 0
Views: 108
Reputation: 537
Perhaps I can give up the inheritance and pull something like this:
class Client:
def __init__(self, base_client):
self.base_client = base_client
...
def main()
base_client = BaseClient(url)
client = Client(base_client)
client.base_client.do_stuff()
client.do_other_stuff()
class BaseClient:
def __init__(self, url):
...
main()
Upvotes: 0
Reputation: 195438
One solution is to define it inside a function:
def get_class():
class Client(BaseClient):
def __init__(self, url):
super().__init__(url)
return Client
class BaseClient:
def __init__(self, url):
self.url = url
Client = get_class()
c = Client('hello')
print(c.url)
Prints:
hello
Note: Do this only if there isn't any other (more clean) solution. The code could get ugly very fast...
Upvotes: 2