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中寻找什么.
我将不胜感激任何帮助.
一种方法是定义subspace和another_subspace作为返回对象的属性,分别提供do_smth和do_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一个单例,但我怀疑性能提升是否值得。
| 归档时间: |
|
| 查看次数: |
972 次 |
| 最近记录: |