首页 > 解决方案 > 是否可以编写一个带有隐藏方法的 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

解决方案


这是一个利用 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毫无问题地从无类型更改为函数类型。

希望这可以帮助!


推荐阅读