我想讓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 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中沒有太多意義... – ChristopheD 2012-04-28 16:03:02
這段代碼很可怕:( – 2012-04-28 16:03:30
在旁註 - 不要使用niceDecorator,使用'functools.wraps()'。 – 2012-04-28 16:07:05