I want a class in Python with an interface like the following:
import myclass
client = myclass.Client("user", "password")
client.users.create("user1")
client.posts.create("user1", "Hello, World!")
Note that instead of just create_user or create_post, I want to specify the method using two dots: users.create / posts.create
I want this particular interface to mimic an HTTP API I'm trying to work with (which has endpoints like "/api/users/create" and "/api/posts/create")
If I define my class as follows in myclass.py:
class Client(object):
def __init__(self, user, pass):
self.user = user
self.pass = pass
Then how do I create these dot-namespaced methods? My first thought is to create subclasses like so:
class Client(object):
def __init__(self, user, pass):
self.user = user
self.pass = pass
self.users = ClientUserAPI()
self.posts = ClientPostAPI()
class ClientUserAPI(object):
def create(self):
# Do some cURL magic
class ClientPostAPI(object):
def create(self):
# Do some cURL magic
However if I do this, then I run into one of two problems (one serious, the other just philosophical / ideological)
- If
ClientUserAPIextends "Client" then the__init__method creates an infinite loop - If
ClientUserAPIextends "object" then it won't directly have access to theself.userandself.passvariables. This means I must create__init__methods on both of the helper classes which do nothing but assignself.userandself.pass. This is redundant not only in code, but also in memory
Is there a better solution?
ClientUserAPIneed access toself.user?client.users..., thenusersmust be an object, meaning an independent class, meaning you must implement it as standalone class. TheClientclass would then merely compose two of those independent classes into oneclientobject. There's no need for it to be the parent class of anything. Memory consumption is pretty irrelevant with these values.usersorpostsare requested but this would need CPU instead of memory.ClientUserAPIneeds access toself.userbecause the user and password must be passed to the HTTP API when a request is made. ThereforeClientUserAPI.createmust send off an HTTP request with the username and password