{"id":137,"date":"2024-01-25T13:32:36","date_gmt":"2024-01-25T13:32:36","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=137"},"modified":"2024-01-25T13:32:37","modified_gmt":"2024-01-25T13:32:37","slug":"python-class-variables","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/25\/python-class-variables\/","title":{"rendered":"Python Class Variables"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn how the Python class variables (or attributes) work.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the Python class variables<\/h2>\n\n\n\n<p>Everything in Python is an object including a\u00a0class. In other words, a class is an object in Python.<\/p>\n\n\n\n<p>When you define a class using the\u00a0<code>class<\/code>\u00a0keyword, Python creates an object with the name the same as the class\u2019s name. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class HtmlDocument: pass<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>This example defines the\u00a0<code>HtmlDocument<\/code>\u00a0class and the\u00a0<code>HtmlDocument<\/code>\u00a0object. The\u00a0<code>HtmlDocument<\/code>\u00a0object has the\u00a0<code>__name__<\/code>\u00a0property:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(HtmlDocument.__name__) <em># HtmlDocument<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>And the\u00a0<code>HTMLDocument<\/code>\u00a0has the type of\u00a0<code>type<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(type(HtmlDocument)) <em># &lt;class 'type'><\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>It\u2019s also an instance of the\u00a0<code>type<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(isinstance(HtmlDocument, type)) <em># True<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Class variables are bound to the class. They\u2019re shared by all instances of that class.<\/p>\n\n\n\n<p>The following example adds the\u00a0<code>extension<\/code>\u00a0and\u00a0<code>version<\/code>\u00a0class variables to the\u00a0<code>HtmlDocument<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class HtmlDocument: extension = 'html' version = '5'<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Both&nbsp;<code>extension<\/code>&nbsp;and&nbsp;<code>version<\/code>&nbsp;are the class variables of the&nbsp;<code>HtmlDocument<\/code>&nbsp;class. They\u2019re bound to the&nbsp;<code>HtmlDocument<\/code>&nbsp;class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Get the values of class variables<\/h2>\n\n\n\n<p>To get the values of class variables, you use the dot notation (<code>.<\/code>). For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(HtmlDocument.extension) <em># html<\/em> print(HtmlDocument.version) <em># 5<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>If you access a class variable that doesn\u2019t exist, you\u2019ll get an\u00a0<code>AttributeError<\/code>\u00a0exception. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>HtmlDocument.media_type<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>AttributeError: type object 'HtmlDocument' has no attribute 'media_type'<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Another way to get the value of a class variable is to use the\u00a0<code>getattr()<\/code>\u00a0function. The\u00a0<code>getattr()<\/code>\u00a0function accepts an object and a variable name. It returns the value of the class variable. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>extension = getattr(HtmlDocument, 'extension') version = getattr(HtmlDocument, 'version') print(extension) <em># html<\/em> print(version) <em># 5<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>If the class variable doesn\u2019t exist, you\u2019ll also get an\u00a0<code>AttributeError<\/code>\u00a0exception. To avoid the exception, you can specify a default value if the class variable doesn\u2019t exist like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>media_type = getattr(HtmlDocument, 'media_type', 'text\/html') print(media_type) <em># text\/html<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Set values for class variables<\/h2>\n\n\n\n<p>To set a value for a class variable, you use the dot notation:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>HtmlDocument.version = 10<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>or you can use the\u00a0<code>setattr()<\/code>\u00a0built-in function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>setattr(HtmlDocument, 'version', 10)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Since Python is a dynamic language, you can add a class variable to a class at runtime after you have created it. For example, the following adds the\u00a0<code>media_type<\/code>\u00a0class variable to the\u00a0<code>HtmlDocument<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>HtmlDocument.media_type = 'text\/html' print(HtmlDocument.media_type)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Similarly, you can use the\u00a0<code>setattr()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>setattr(HtmlDocument, media_type, 'text\/html') print(HtmlDocument.media_type)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Delete class variables<\/h2>\n\n\n\n<p>To delete a class variable at runtime, you use the\u00a0<code>delattr()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>delattr(HtmlDocument, 'version')<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Or you can use the\u00a0<code>del<\/code>\u00a0keyword:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>del HtmlDocument.version<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Class variable storage<\/h2>\n\n\n\n<p>Python stores class variables in the\u00a0<code>__dict__<\/code>\u00a0attribute. The\u00a0<code>__dict__<\/code>\u00a0is a mapping proxy, which is a dictionary. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from pprint import pprint class HtmlDocument: extension = 'html' version = '5' HtmlDocument.media_type = 'text\/html' pprint(HtmlDocument.__dict__)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>mappingproxy({'__dict__': &lt;attribute '__dict__' of 'HtmlDocument' objects>, '__doc__': None, '__module__': '__main__', '__weakref__': &lt;attribute '__weakref__' of 'HtmlDocument' objects>, 'extension': 'html', 'media_type': 'text\/html', 'version': '5'})<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>As clearly shown in the output, the&nbsp;<code>__dict__<\/code>&nbsp;has three class variables:&nbsp;<code>extension<\/code>,&nbsp;<code>media_type<\/code>, and&nbsp;<code>version<\/code>&nbsp;besides other predefined class variables.<\/p>\n\n\n\n<p>Python does not allow you to change the\u00a0<code>__dict__<\/code>\u00a0directly. For example, the following will result in an error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>HtmlDocument.__dict__&#91;'released'] = 2008<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>TypeError: 'mappingproxy' object does not support item assignment<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>However, you can use the&nbsp;<code>setattr()<\/code>&nbsp;function or dot notation to indirectly change the&nbsp;<code>__dict__<\/code>&nbsp;attribute.<\/p>\n\n\n\n<p>Also, the key of the&nbsp;<code>__dict__<\/code>&nbsp;are strings that will help Python speeds up the variable lookup.<\/p>\n\n\n\n<p>Although Python allows you to access class variables through the\u00a0<code>__dict__<\/code>\u00a0dictionary, it\u2019s not a good practice. Also, it won\u2019t work in some situations. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(HtmlDocument.__dict__&#91;'type']) <em># BAD CODE<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Callable class attributes<\/h2>\n\n\n\n<p>Class attributes can be any object such as a function.<\/p>\n\n\n\n<p>When you add a function to a class, the function becomes a class attribute. Since a function is callable, the class attribute is called a callable class attribute. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from pprint import pprint class HtmlDocument: extension = 'html' version = '5' def render(): print('Rendering the Html doc...') pprint(HtmlDocument.__dict__)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>mappingproxy({'__dict__': &lt;attribute '__dict__' of 'HtmlDocument' objects>, '__doc__': None, '__module__': '__main__', '__weakref__': &lt;attribute '__weakref__' of 'HtmlDocument' objects>, 'extension': 'html', 'render': &lt;function HtmlDocument.render at 0x0000010710030310>, 'version': '5'}) Rendering the Html doc...<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>In this example, the&nbsp;<code>render<\/code>&nbsp;is a class attribute of the&nbsp;<code>HtmlDocument<\/code>&nbsp;class. Its value is a function.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn how the Python class variables (or attributes) work. Introduction to the Python class variables Everything in Python is an object including a\u00a0class. In other words, a class is an object in Python. When you define a class using the\u00a0class\u00a0keyword, Python creates an object with the name the same as [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[25],"tags":[],"class_list":["post-137","post","type-post","status-publish","format-standard","hentry","category-1-classes-and-objects"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/137","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=137"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/137\/revisions"}],"predecessor-version":[{"id":138,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/137\/revisions\/138"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=137"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=137"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=137"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}