Skip to content

Instantly share code, notes, and snippets.

@JeroenDeDauw
Created December 12, 2016 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeroenDeDauw/a935a21b7bdd03b9b86e91cef34313c1 to your computer and use it in GitHub Desktop.
Save JeroenDeDauw/a935a21b7bdd03b9b86e91cef34313c1 to your computer and use it in GitHub Desktop.
Python properties
# Tested with Python 3.5
# Fails on 2.x
from unittest import TestCase, main
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def get_double_x(self):
return self._x * 2
def get_y(self):
return self._y
def set_y(self, y):
self._y = y
xx = property(get_double_x)
y = property(get_y, set_y)
@property
def property_using_decorator(self):
return self._y
class TestProperties(TestCase):
def test_can_construct(self):
point = Point(y=2, x=4)
self.assertEqual(point.y, 2)
def test_can_set_property_with_setter(self):
point = Point(y=2, x=4)
point.y = 42
self.assertEqual(point.y, 42)
def test_can_get_property_with_computing_setter(self):
point = Point(y=2, x=4)
self.assertEqual(point.xx, 8)
def test_set_property_without_setter__yay_python(self):
point = Point(y=2, x=4)
with self.assertRaises(AttributeError):
point.xx = 42
def test_cannot_set_decorator_based_property_without_setter(self):
point = Point(y=2, x=4)
with self.assertRaises(AttributeError):
point.property_using_decorator = 42
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment