{"id":2574,"date":"2021-10-17T07:31:52","date_gmt":"2021-10-17T07:31:52","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=2574"},"modified":"2025-03-31T10:10:31","modified_gmt":"2025-03-31T10:10:31","slug":"python-readonly-property","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-oop\/python-readonly-property\/","title":{"rendered":"Python Readonly Property"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to define Python readonly property and how to use it to define computed properties.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-python-readonly-property'>Introduction to the Python readonly property <a href=\"#introduction-to-the-python-readonly-property\" class=\"anchor\" id=\"introduction-to-the-python-readonly-property\" title=\"Anchor for Introduction to the Python readonly property\">#<\/a><\/h2>\n\n\n\n<p>To define a readonly <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-properties\/\">property<\/a>, you need to create a property with only the getter. However, it is not truly read-only because you can always access the underlying attribute and change it.<\/p>\n\n\n\n<p>The read-only properties are useful in some cases such as for computed properties.<\/p>\n\n\n\n<p>The following example defines a class called <code>Circle<\/code> that has a <code>radius<\/code> attribute and an <code>area()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import<\/span> math\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Circle<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, radius)<\/span>:<\/span>\n        self.radius = radius\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">area<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> math.pi * self.radius ** <span class=\"hljs-number\">2<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And the following creates a new <code>Circle<\/code> object and returns its area:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">c = Circle(<span class=\"hljs-number\">10<\/span>)\nprint(c.area())<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-number\">314.1592653589793<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here&#8217;s the complete script:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">import math\n\n\nclass Circle:\n    def __init__(self, radius):\n        self.radius = radius\n\n    def area(self):\n        return math.pi * self.radius ** 2\n    \nc = Circle(10)\nprint(c.area())    <\/code><\/span><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=aW1wb3J0IG1hdGgKCgpjbGFzcyBDaXJjbGU6CiAgICBkZWYgX19pbml0X18oc2VsZiwgcmFkaXVzKToKICAgICAgICBzZWxmLnJhZGl1cyA9IHJhZGl1cwoKICAgIGRlZiBhcmVhKHNlbGYpOgogICAgICAgIHJldHVybiBtYXRoLnBpICogc2VsZi5yYWRpdXMgKiogMgogICAgCmMgPSBDaXJjbGUoMTApCnByaW50KGMuYXJlYSgpKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\">314<span class=\"hljs-selector-class\">.1592653589793<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This code works perfectly fine.<\/p>\n\n\n\n<p>But it would be more natural that the area is a property of the <code>Circle<\/code> object, not a method. To make the <code>area()<\/code> method as a property of the <code>Circle<\/code> class, you can use the <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-property-decorator\/\"><code>@property<\/code> decorator<\/a> as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import<\/span> math\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Circle<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, radius)<\/span>:<\/span>\n        self.radius = radius\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">area<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> math.pi * self.radius ** <span class=\"hljs-number\">2<\/span>\n\n\nc = Circle(<span class=\"hljs-number\">10<\/span>)\nprint(c.area)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=aW1wb3J0IG1hdGgKCgpjbGFzcyBDaXJjbGU6CiAgICBkZWYgX19pbml0X18oc2VsZiwgcmFkaXVzKToKICAgICAgICBzZWxmLnJhZGl1cyA9IHJhZGl1cwoKICAgIEBwcm9wZXJ0eQogICAgZGVmIGFyZWEoc2VsZik6CiAgICAgICAgcmV0dXJuIG1hdGgucGkgKiBzZWxmLnJhZGl1cyAqKiAyCgoKYyA9IENpcmNsZSgxMCkKcHJpbnQoYy5hcmVhKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>The area is calculated from the <code>radius<\/code> attribute. Therefore, it&#8217;s often called a calculated or computed property.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='caching-calculated-properties'>Caching calculated properties <a href=\"#caching-calculated-properties\" class=\"anchor\" id=\"caching-calculated-properties\" title=\"Anchor for Caching calculated properties\">#<\/a><\/h2>\n\n\n\n<p>Suppose you create a new circle object and access the area property many times. Each time, the area needs to be recalculated, which is not efficient.<\/p>\n\n\n\n<p>To make it more performant, you need to recalculate the area of the circle only when the radius changes. If the radius doesn&#8217;t change, you can reuse the previously calculated area.<\/p>\n\n\n\n<p>To do it, you can use the caching technique:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, calculate the area and save it in a cache.<\/li>\n\n\n\n<li>Second, if the radius changes, reset the area. Otherwise, return the area directly from the cache without recalcuation. <\/li>\n<\/ul>\n\n\n\n<p>The following defines the new <code>Circle<\/code> class with cached <code>area<\/code> property:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import<\/span> math\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Circle<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, radius)<\/span>:<\/span>\n        self._radius = radius\n        self._area = <span class=\"hljs-literal\">None<\/span>\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">radius<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self._radius\n\n<span class=\"hljs-meta\">    @radius.setter<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">radius<\/span><span class=\"hljs-params\">(self, value)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> value &lt; <span class=\"hljs-number\">0<\/span>:\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'Radius must be positive'<\/span>)\n\n        <span class=\"hljs-keyword\">if<\/span> value != self._radius:\n            self._radius = value\n            self._area = <span class=\"hljs-literal\">None<\/span>\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">area<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> self._area <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-literal\">None<\/span>:\n            self._area = math.pi * self.radius ** <span class=\"hljs-number\">2<\/span>\n\n        <span class=\"hljs-keyword\">return<\/span> self._area<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=aW1wb3J0IG1hdGgKCgpjbGFzcyBDaXJjbGU6CiAgICBkZWYgX19pbml0X18oc2VsZiwgcmFkaXVzKToKICAgICAgICBzZWxmLl9yYWRpdXMgPSByYWRpdXMKICAgICAgICBzZWxmLl9hcmVhID0gTm9uZQoKICAgIEBwcm9wZXJ0eQogICAgZGVmIHJhZGl1cyhzZWxmKToKICAgICAgICByZXR1cm4gc2VsZi5fcmFkaXVzCgogICAgQHJhZGl1cy5zZXR0ZXIKICAgIGRlZiByYWRpdXMoc2VsZiwgdmFsdWUpOgogICAgICAgIGlmIHZhbHVlIDwgMDoKICAgICAgICAgICAgcmFpc2UgVmFsdWVFcnJvcignUmFkaXVzIG11c3QgYmUgcG9zaXRpdmUnKQoKICAgICAgICBpZiB2YWx1ZSAhPSBzZWxmLl9yYWRpdXM6CiAgICAgICAgICAgIHNlbGYuX3JhZGl1cyA9IHZhbHVlCiAgICAgICAgICAgIHNlbGYuX2FyZWEgPSBOb25lCgogICAgQHByb3BlcnR5CiAgICBkZWYgYXJlYShzZWxmKToKICAgICAgICBpZiBzZWxmLl9hcmVhIGlzIE5vbmU6CiAgICAgICAgICAgIHNlbGYuX2FyZWEgPSBtYXRoLnBpICogc2VsZi5yYWRpdXMgKiogMgoKICAgICAgICByZXR1cm4gc2VsZi5fYXJlYQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, set the <code>_area<\/code> to <code>None<\/code> in the <code>__init__<\/code> method. The _area attribute is the cache that stores the calculated area.<\/p>\n\n\n\n<p>Second, if the radius changes (in the setter), reset the <code>_area<\/code> to <code>None<\/code>.<\/p>\n\n\n\n<p>Third, define the <code>area<\/code> computed property. The <code>area<\/code> property returns <code>_area<\/code> if it is not <code>None<\/code>. Otherwise, calculate the area, save it into the <code>_area<\/code>, and return it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Define only the getter to make a property readonly<\/li>\n\n\n\n<li>Do use computed property to make the property of a class more natural<\/li>\n\n\n\n<li>Use caching computed properties to improve the performance.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=readonly-property\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"2574\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-readonly-property\/\"\n\t\t\t\tdata-post-title=\"Python Readonly Property\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"2574\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-readonly-property\/\"\n\t\t\t\tdata-post-title=\"Python Readonly Property\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>in this tutorial, you&#8217;ll learn how to define Python readonly property and how to use it to define computed properties.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":417,"menu_order":19,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-2574","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2574","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=2574"}],"version-history":[{"count":2,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2574\/revisions"}],"predecessor-version":[{"id":7311,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2574\/revisions\/7311"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/417"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=2574"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}