Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active October 18, 2017 04:39
Show Gist options
  • Select an option

  • Save dboyliao/321d0ab5657fba80989f9fe428755874 to your computer and use it in GitHub Desktop.

Select an option

Save dboyliao/321d0ab5657fba80989f9fe428755874 to your computer and use it in GitHub Desktop.
@Property example
#!/usr/bin/env python3
# -*- coding:utf8 -*-
from __future__ import print_function
from copy import deepcopy
class MyAwesomObject(object):
def __init__(self, private_value):
self.__private_value = private_value
@property
def private_value(self):
return deepcopy(self.__private_value)
@private_value.setter
def private_value(self, new_value):
raise RuntimeError("Public access to private value is not allowed")
# you can also do type checking here and update private value
# instead of raising RuntimError
if __name__ == "__main__":
my_obj = MyAwesomObject([1, 2, 3])
ori_list = my_obj.private_value
ori_list[0] = 10
print(ori_list)
print(my_obj.private_value)
try:
my_obj.private_value = 3
except RuntimeError as e:
print("Can not assign value to private variable :)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment