【问题标题】:How to "namespace" methods in Python class如何在 Python 类中“命名空间”方法
【发布时间】:2018-07-02 13:09:52
【问题描述】:

我想要一个 Python 中的类,其接口如下:

import myclass

client = myclass.Client("user", "password")

client.users.create("user1")
client.posts.create("user1", "Hello, World!")

请注意,我想使用两个点来指定方法,而不仅仅是create_usercreate_postusers.create / posts.create

我希望这个特定的接口能够模仿我正在尝试使用的 HTTP API(它具有像“/api/users/create”和“/api/posts/create”这样的端点)

如果我在myclass.py 中定义我的类如下:

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

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

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

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

  1. 如果 ClientUserAPI 扩展“客户端”,则 __init__ 方法会创建一个无限循环
  2. 如果ClientUserAPI 扩展了“对象”,那么它将无法直接访问self.userself.pass 变量。这意味着我必须在两个助手类上创建__init__ 方法,这些方法除了分配self.userself.pass 之外什么都不做。这不仅在代码中是多余的,而且在内存中也是多余的

有没有更好的解决方案?

【问题讨论】:

  • 你所拥有的看起来不错。为什么ClientUserAPI 需要访问self.user
  • 如果你坚持client.users...,那么users必须是一个对象,意思是一个独立的类,意味着你必须将它作为一个独立的类来实现。然后Client 类只会将这些独立类中的两个组合成一个client 对象。它没有必要成为任何东西的父类。内存消耗与这些值无关。
  • 在其他语言中,例如Java 你可以创建内部类,但这些对象在内部也会持有对外部对象的引用。在 Python 中你应该做同样的事情,但是使用显式的构造函数参数。
  • 唯一的替代方法是在每次请求属性usersposts 时按需创建一个对象,但这需要CPU 而不是内存。
  • ClientUserAPI 需要访问self.user,因为在发出请求时必须将用户名和密码传递给 HTTP API。因此ClientUserAPI.create 必须使用用户名和密码发送 HTTP 请求

标签: python class namespaces


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2013-01-08
    • 2014-03-24
    • 2021-07-22
    • 2013-05-17
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    相关资源
    最近更新 更多