有没有可能编写一个带有隐藏方法的Python类,该方法只有在设置了特定属性时才可调用?

2024-10-01 15:49:25 发布

您现在位置: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

Tags: the文本tokenerrorsome编码器sentenceclass
1条回答
网友
1楼 · 发布于 2024-10-01 15:49:25

下面是一个利用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从none类型更改为函数类型,而不会出现任何问题

希望这有帮助

相关问题 更多 >

    热门问题