python - python上有动态类型吗?
问题描述
我有一个特定的打字用例,我觉得很难实现。
我的 python 代码库中有“服务”类的概念,这些类具有一些我想“公开”的功能,因此只有在使用 API 时它们才可用。Service的实现是这样的:
class MyService(BaseService):
def normal_function(self):
pass
@exposed
def exposed_function(self):
pass
这件事背后发生的@exposed
事情是,它为包装的方法添加了一个独特的属性,它允许使用它的人知道哪些函数是“公开的”或没有。
我希望使一种类型足够聪明,以了解只有“公开”功能可用。
有任何想法吗?
解决方案
您可以使用名称修饰:
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 中不存在私有变量和方法,但名称修饰可能是您可以实现的最接近于实现类私有行为的方法。
推荐阅读
- javascript - 将 API 调用的 Pdf 响应转换为 Blob 并生成 Blob Url
- operator-keyword - 无法理解 systemc '<<' 操作
- laravel - 错误:Laravel 中此集合实例上不存在属性 [kpi_description]
- postman - 邮递员 - 突出显示特定单元格
- c - 如何解释linux内核陷阱错误行?
- ruby-on-rails - 如何在 Rails 中显示索引翻译(rails-i18n)?
- javascript - 使用 Firebase 处理用户身份验证错误
- ios - 我可以通过 iOS Developer University Program 将应用程序发布到 Apple Store
- javascript - 如何在 Gatsby 中使用 GraphQL 查询,该查询在高级自定义字段 (ACF) 中返回一个数组?
- regex - 从 PHP 到 JS 的正则表达式