python - 是否可以编写一个带有隐藏方法的 Python 类,该方法只有在设置了特定属性时才能调用?
问题描述
我创建了一种编码器类,它接受文本数据并将它们转换为整数并返回。
但是,此信息是业务敏感信息,因此我不希望类的解码器或编码器映射可调用,除非输入了特定令牌
例如,我想要下面的代码。但是由于一个类的所有属性和方法都是公开的(据我所知),我不知道如何处理它。甚至可能吗?
import pickle
class EncoderDecoder:
# something happens here
# dump the class
# load the class
ed = EncoderDecoder(*args, **kwargs)
ed.encode(sentence) # raises some error
ed.decode(sentence) # raises some error
ed.set_token = "pasword1234"
ed.encode(sentence) # returns encoded
ed.decode(sentence) # returns decoded
# the user can't access set_token property setter or decoder method
解决方案
这是一个利用 Python 如何处理类成员的简单解决方案。
class Example:
def __init__(self):
self.method = None
def enable_method():
def method():
# do thing
pass
self.method = method
那应该对你有用。因为实际的方法定义只存在于 的上下文中enable_method
,所以外部无法访问。由于 Python 不是类型安全的,因此您可以self.method
毫无问题地从无类型更改为函数类型。
希望这可以帮助!
推荐阅读
- python - eBay API 未发送正确的输出作为响应(未发回列表)
- amazon-web-services - 跨账户共享使用 AWS 托管密钥加密的 AWS EC2 映像
- reactjs - 如何在 Hooks 中获取子组件的引用
- node.js - npm init 抛出错误代码 ENOENT errno -4058
- tensorflow - MutableHashTable 是如何放置在参数服务器上的,是否可以并行更新哈希表并加锁?
- php - 重力形式:单选按钮标签的 ACF 字段
- excel - 查找 2 个工作表中特定列之间的差异
- python - 在 Python/Django 测试中使用类使代码更可重用
- reactjs - 如何在 React 中将类组件对象转换为功能组件对象?
- hive - Hive:计算只分配给集群中的一个节点