python - 这段代码真的是私有(private)的吗? (Python)

标签 python private

我试图让 python 允许私有(private)变量,所以我做了这个装饰器,你把它放在类的开头,这样每个函数都会得到一个额外的私有(private)参数,它们可以修改成他们想要的。据我所知,不可能从类外获取变量,但我不是专业人士。

谁能找到一种方法侵入私有(private)对象并从中获取值?有比这更好的方法吗?

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()

最佳答案

简而言之:不要这样做。

There is no need to make things truly private in Python .使用您的软件的人可以看到某些内容是否被标记为私有(private)(变量名称以 _ 开头),所以他们知道。如果他们仍然想访问它,为什么要阻止他们?

我敢肯定还有一种方法可以解决您的代码 - Python 具有数量惊人的内省(introspection)代码,并且修改类很容易。如果有人真的想得到它,几乎不可能锁定任何东西。

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

关于python - 这段代码真的是私有(private)的吗? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10365193/

相关文章:

python - 如何测试Django的UpdateView?

python - 通用详细信息 View ProfileView必须使用对象pk或子弹调用

python - TensorFlow - 'split_dim' Op 的输入 'Split' 的 float32 类型与预期的 int32 类型不匹配

python - 在 Python 中抓取表格时,返回一个空表格

C++ 访问私有(private) vector 值

python:以有组织的方式引用 "private"变量的名称

java - 如何从私有(private)方法调用数组?

java - 我不明白私有(private)构造函数如何不能在外部创建实例并阻止子类化(当他这样做时!)

python - 如何使用 Python 的 matplotlib 绘制 map 以便也包括小岛国?

c++ - Comeau vs g++ [又一个错误]