首页 > 解决方案 > python上有动态类型吗?

问题描述

我有一个特定的打字用例,我觉得很难实现。

我的 python 代码库中有“服务”类的概念,这些类具有一些我想“公开”的功能,因此只有在使用 API 时它们才可用。Service的实现是这样的:

class MyService(BaseService):
    def normal_function(self):
        pass

    @exposed
    def exposed_function(self):
        pass

这件事背后发生的@exposed事情是,它为包装的方法添加了一个独特的属性,它允许使用它的人知道哪些函数是“公开的”或没有。

我希望使一种类型足够聪明,以了解只有“公开”功能可用。

有任何想法吗?

标签: pythonpython-3.xpython-typing

解决方案


您可以使用名称修饰

class MyService():
    def __normal_function(self):
        pass

    def exposed_function(self):
        pass

my_service = MyService()
my_service.exposed_function() # this works, user can use the exposed function
my_service.__normal_function() # error: MyService instance has no attribute '__normal_function'
my_service._MyService__normal_function() # normal_function can only be called using its "mangled" name

在这种情况下,普通函数的名称 - __normal_function- 将在文本上替换为_MyService__normal_function,因此用户将无法使用其“原始”名称调用该函数。

请注意,仍然可以在类外部调用普通函数,因为 Python 中不存在私有变量和方法,但名称修饰可能是您可以实现的最接近于实现类私有行为的方法。


推荐阅读