如何"命名空间" Python类中的方法

时间:2018-01-23 16:21:23

标签: python class namespaces

我想在Python中使用如下界面的类:

gst-launch-1.0 pulsesrc device=alsa_input.pci-0000_00_05.0.analog-stereo ! queue ! \
           audioconvert ! \
           audioresample ! tee name=t ! queue ! \
       kaldinnet2onlinedecoder \
       use-threaded-decoder=0 \
       nnet-mode=3 \
       word-syms=/opt/models/fr/words.txt \
       mfcc-config=/opt/models/fr/mfcc_hires.conf \
       ivector-extraction-config=/opt/models/fr/ivector-extraction/ivector_extractor.conf \
       phone-syms=/opt/models/fr/phones.txt \
       frame-subsampling-factor=3 \
       max-active=7000 \
       beam=13.0 \
       lattice-beam=8.0 \
       acoustic-scale=1 \
       do-endpointing=1 \
       endpoint-silence-phones=1:2:3:4:5:16:17:18:19:20 \
       traceback-period-in-secs=0.25 \
       num-nbest=2 \
       chunk-length-in-secs=0.25 \
       fst=/opt/models/fr/HCLG.fst \
       model=/opt/models/fr/final.mdl \
       ! filesink async=0 location=/dev/stdout t. ! queue ! autoaudiosink async=0

请注意,我不是仅使用import myclass client = myclass.Client("user", "password") client.users.create("user1") client.posts.create("user1", "Hello, World!") create_user,而是使用两个点指定方法:create_post / users.create

我希望这个特殊的界面能够模仿我尝试使用的HTTP API(其中包含" / api / users / create"和#34; / api / posts /等端点创建&#34)

如果我在posts.create中按如下方式定义我的课程:

myclass.py

那我该如何创建这些点名称空间的方法呢?我的第一个想法是创建类似的子类:

class Client(object):
    def __init__(self, user, pass):
        self.user = user
        self.pass = pass

但如果我这样做,那么我会遇到两个问题之一(一个是严重的,另一个只是哲学/意识形态的)

  1. 如果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 延伸"客户"然后ClientUserAPI方法创建一个无限循环
  2. 如果__init__延伸"对象"然后,它无法直接访问ClientUserAPIself.user变量。这意味着我必须在两个辅助类上创建self.pass方法,除了分配__init__self.user之外什么都不做。这不仅在代码中是冗余的,而且在内存中也是多余的
  3. 有更好的解决方案吗?

1 个答案:

答案 0 :(得分:5)

class Client:
  def __init__(self):
    self.users = ClientUserAPI(self)
    self.posts = ClientPostAPI(self)

class ClientUserAPI:
  def __init__(self, client):
    self.client = client

class ClientPostAPI:
  def __init__(self, client):
    self.client = client
相关问题