简体   繁体   中英

Python class interface design

Is there a way to easily expose the APi of an internal object of a python class without retyping every API of that object? For example, I write a redis replica class and all my functions are like

def get_connection(self, name):
    ........
    host, conn = self.colo_rings[name]
    return conn

def hgetall(self, name):
    return self.get_connection(name).hgetall(name)

def hset(self, name, key, value):
    return self.get_connection(name).hset(name, key, value)

def hsetnx(self, name, key, value):
    return self.get_connection(name).hsetnx(name, key, value)

def hdel(self, name, *key, colo=None):
    return self.get_connection(name).hdel(name, *key)

How can I improve this code and make it not that "ugly"?

You should be able to use something similar to this:

class B(object):
  def __getattribute__(self, method):
    try:
      return getattr(self, method)
    except:
      return getattr(self.get_connection(key), method)

The advantage here is that you can still use methods that don't exist on your connection by defining them on the class, but anything that you don't define and that exists on the connection will be used when you try to access it via myB.hgetall() (for example).

For completeness - __getattr__ is sufficient:

class B(object):
  def __getattr__(self, method):
    return getattr(self.get_connection(key), method)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM