Skip to content

Instantly share code, notes, and snippets.

@astrojuanlu
Created November 18, 2020 18:37
Show Gist options
  • Save astrojuanlu/082df621473c3e0de27993b58955e306 to your computer and use it in GitHub Desktop.
Save astrojuanlu/082df621473c3e0de27993b58955e306 to your computer and use it in GitHub Desktop.
Comparing @Property access versus direct access
In [1]: class Foo:
...: def __init__(self, a, b):
...: self._a = a
...: self.b = b
...: @property
...: def a(self):
...: return self._a
...:
In [2]: Foo.a
Out[2]: <property at 0x7f5aec3e28b0>
In [3]: Foo.b
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-6cbe443c09a1> in <module>
----> 1 Foo.b
AttributeError: type object 'Foo' has no attribute 'b'
In [4]: f = Foo(1, 1)
In [5]: f.a
Out[5]: 1
In [6]: f.b
Out[6]: 1
In [7]: %timeit f.a
109 ns ± 1.31 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [8]: %timeit f.b
47.4 ns ± 3.12 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment