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



我正在尝试使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 function in
    #the class along with self which has been renamed
    #as pbl (public).
    @niceDecorator
    #this is the decorator that gets applied to every function
    #in the class. in makes it also accept the private argument
    def decorate(func):
        def run(pub, *args, **kwargs):
            return func(pub,prv, *args, **kwargs)
        return run
    #this loops through every function in the class and applies the decorator
    for func in cls.__dict__.values():
        if callable(func):
            setattr(cls, func.__name__, decorate(getattr(cls, func.__name__)))
    return cls
#this is the class we are testing the private decorator with.
#this is what the user would program
@usePrivate
class test():
    #sets the value of the private variable
    def setValue(pbl,prv,arg):
        #pbl (public) is another name for self
        #prv (private) acts just like self except its private
        prv.test=arg
    #gets the value of the private variable
    def getValue(pbl,prv):
        return prv.test
a=test()
a.setValue(3)
print a.getValue()

简而言之:不要这样做。

没有必要

在Python中使事情真正私密。使用您的软件的人可以看到某些内容是否被标记为私有(变量名称以 _ 开头),以便他们知道。如果他们仍然想访问它,为什么要阻止他们?

我相信还有一种方法可以绕过你的代码 - Python 有大量的内省代码,修改类很容易做到。如果有人真的想去,几乎不可能锁定任何东西。

同样值得注意的是,在Python中,setters/getters是没有意义的。目的是允许您在设置/获取属性时添加代码,python允许您使用内置的property()来执行此操作。

这是一个有趣的想法,但是您用于装饰器的包装器函数将在其func_closure属性中引用"private"对象。因此,您的"私有"变量可作为a.getValue.func_closure[0].cell_contents.test访问。(您可以使用任何包装的函数来访问您的"私有"对象,而不仅仅是getValue

通常,这种技术只会惹恼使用您的代码的其他程序员。

总有一种方法可以在Python中获取内容,特别是如果你有原始源代码可以阅读。 使用 kindall 的示例,将这些行添加到文件的末尾:

print a.getValue.im_func.func_closure[0].cell_contents.test
a.getValue.im_func.func_closure[0].cell_contents.test = 17
print a.getValue()

真的,不要这样做。 Python人说"不要为私有变量而烦恼"是有原因的。

正如其他人所说,仍然有一种方法可以获取私有变量。但是,您仍然可以在 c++ 中使用私有变量。请考虑以下C++示例:

class PrivateEye
{
    private:
    int a;
    double b;
    char c;
    public:
    // ... public functions ...
};
PrivateEye detective;
double privateB = *((double *) ((void *) &detective + sizeof(detective.a)));

如您所见,访问私有变量需要大量工作,因此执行此操作的人需要了解足够的知识才能了解风险。因此,如果您有程序员使用您的_attribute私有属性,您发布的解决方案将有效地让他们在弄乱私有属性之前考虑一下。使用__attribute(双下划线)会导致一些名称重整,这也具有相同的效果,导致人们在决定访问"私有"属性之前多做一些思考。

编辑:根据访问私有成员中的第二个答案,C++标准不能保证类中成员变量的顺序,因此您可能需要进行一些实验才能访问上面C++示例中所需的私有变量。

最新更新