Python3中类的命名空间

mDe*_*evv 10 python namespaces class python-3.x

我是Python的新手,我想知道是否有任何方法可以将方法聚合到'子空间'中.我的意思是类似于这种语法:

smth = Something()
smth.subspace.do_smth()
smth.another_subspace.do_smth_else()
Run Code Online (Sandbox Code Playgroud)

我正在编写一个API包装器,我将会有很多非常相似的方法(只有不同​​的URI),所以我将它们放在几个引用API请求类别的子空间中会很好.换句话说,我想在类中创建名称空间.我不知道这在Python中是否可行,并且知道在Google中寻找什么.

我将不胜感激任何帮助.

Jon*_*ler 5

一种方法是定义subspaceanother_subspace作为返回对象的属性,分别提供do_smthdo_smth_else

class Something:
    @property
    def subspace(self):
        class SubSpaceClass:
            def do_smth(other_self):
                print('do_smth')
        return SubSpaceClass()

    @property
    def another_subspace(self):
        class AnotherSubSpaceClass:
            def do_smth_else(other_self):
                print('do_smth_else')
        return AnotherSubSpaceClass()
Run Code Online (Sandbox Code Playgroud)

哪个做你想要的:

>>> smth = Something()
>>> smth.subspace.do_smth()
do_smth
>>> smth.another_subspace.do_smth_else()
do_smth_else
Run Code Online (Sandbox Code Playgroud)

根据您打算使用这些方法的目的,您可能想要制作SubSpaceClass一个单例,但我怀疑性能提升是否值得。

  • @mDevv:我不同意。正如 PM 指出的那样,这每次都会创建一个新的类对象。至少将这些类移出方法。接下来,您还必须担心共享状态。我会考虑重构您的 API 以使其不需要命名空间? (2认同)