Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: Getters and setters
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: Getters and setters
In languages such as Java, a common style is to use getters and setters for instance variables using functions get and set.

Here is an example in Python (that ignores any error checking).

2. Explicit get and set
Here is the Python code [#1]

Here is the output of the Python code.


3. Notes
Note: In Java, the colorDict1 can be hidden from outside - private or protected. In Python, it can not be easily hidden - private or protected. Here is the Python code [#2]

Here is the output of the Python code.


4. Summary
In summary, the use of __getitem__ and __setitem__ makes for nicer code.

Before: (without)
colors1.set(color2,"FFFF00") hex2 = colors1.get(color2)

After: (with)
colors1[color2] = "FFFF00" hex2 = colors1[color2]


5. Dictionaries and lists
It can now be seen that the getting and setting of dictionary keys and list elements using square brackets is a much more general concept in the Python language.

Note: C# has this feature using square brackets. Java does not.

by RS  admin@robinsnyder.com : 1024 x 640