关于Python私有属性的一些tips

看看代码的执行结果吧

class Foo(object):
    def __init__(self, local):
        object.__setattr__(self, '_Foo__local', local)

    def get(self):
        return self.__local


a = Foo('a')
print(a.get())
#结果a

再来一个

class Bar(object):
    def __init__(self, name):
        self.__name = name


b = Bar('hello')
print(b._Bar__name)
# 结果hello

Flask中关于代理的使用

from werkzeug.local import LocalStack, LocalProxy
from flask import Flask
app  = Flask()
app.run()

test_stack = LocalStack()
test_stack.push({'abc': '123'})
test_stack.push({'abc': '1234'})


def get_item():
    return test_stack.pop()


item = LocalProxy(get_item)

print(item['abc'])
print(item['abc'])

这个呢?

from werkzeug.local import LocalStack
test_stack = LocalStack()
test_stack.push({'abc': '123'})
test_stack.push({'abc': '1234'})

def get_item():
    return test_stack.pop()

item = get_item()

print(item['abc'])
print(item['abc'])

你可能感兴趣的:(关于Python私有属性的一些tips)