相关疑难解决方法(0)

Python中的"私有"(实现)类

我正在编写一个由两部分组成的小型Python模块:

  • 一些定义公共接口的函数,
  • 上述函数使用的实现类,但在模块外部没有意义.

起初,我决定通过使用它在函数内部定义它来"隐藏"这个实现类,但这妨碍了可读性,如果多个函数重用同一个类,则不能使用它.

那么,除了评论和文档字符串之外,是否有一种机制将类标记为"私有"或"内部"?我知道下划线机制,但据我所知它只适用于变量,函数和方法名称.

python access-modifiers

97
推荐指数
7
解决办法
7万
查看次数

这段代码真的是私密的吗?(蟒蛇)

我试图让python允许私有变量,所以我把这个装饰器放在一个类的乞讨中,这样每个函数都会获得一个额外的私有参数,他们可以修改它们是他们想要的.据我所知,从课外获取变量是不可能的,但我不是专业人士.

任何人都可以找到一种方法来入侵私有对象并从中获取值?有没有比这更好的方法呢?

python 2.7

#this is a decorator that decorates another decorator. it makes the decorator
#not loose things like names and documentation when it creates a new function
def niceDecorator(decorator):
    def new_decorator(f):
        g = decorator(f)
        g.__name__ = f.__name__
        g.__doc__ = f.__doc__
        g.__dict__.update(f.__dict__)
        return g
    new_decorator.__name__ = decorator.__name__
    new_decorator.__doc__ = decorator.__doc__
    new_decorator.__dict__.update(decorator.__dict__)
    return new_decorator

@niceDecorator
#this is my private decorator
def usePrivate(cls):

    prv=type('blank', (object,), {})
    #creates a blank object in the local scope
    #this object will be passed into every …
Run Code Online (Sandbox Code Playgroud)

python private

2
推荐指数
2
解决办法
1381
查看次数

标签 统计

python ×2

access-modifiers ×1

private ×1