I wanted to hit this topic for a while - but did not have enough material (in Panda3D) to support my thoughts.
There are a lot of Panda3D examples where the code is one class. That’s fine. In fact, it is often correct. There is a time to refactor code, there is a level of design to consider always - and there is balance between over and under engineering a solution (a simple program simply does not warrant a complex design).
Thus, for Issues 1 - 4 of MGF, the code has been in one class. Come Issue 5 and it’s beginning to look more like a game - and needs to be coded appropriately to support the immediate future.
This is an example of recognising when to refactor/change design and then applying a sensible design to support a code base:
I didn’t want to post in showcase as, aside from a bit of sound/HUD code, there’s nothing special in it other than taking an existing piece of code and refactoring it in anticipation of the future.
The article also attempts to give a short overview of the key object oriented concepts and benefits along with listing the essential qualities of a good design.
Regards to all,
Regarding the mention of private variables on page 2, you should be able to prefix any variable with a double underscore which will invoke name mangling in exactly the same way as it applies to a function.
self.__myvar = True
print not self.__myvar
baseclass = BaseClass()
subclass = SubClass()
Traceback (most recent call last):
File "test.py", line 15, in <module>
File "test.py", line 10, in print_info
AttributeError: 'SubClass' object has no attribute '_SubClass__myvar'
You are correct. I will update the text accordingly.
In both cases, name mangling is a bit of hack on the object oriented front. Accessing/modifying private variables is still always possible. Shame.
Updated text reads:
“Private methods are useful in the situation where you feel a class needs a method - but only for internal use. You can do the same with member variables, make them private via a double-underscore prefix. Sadly, in Python, it’s a bit of a hack under the hood. The double-underscore prefix actually causes something called name mangling (to be discussed in the future!). Private variables, with a bit of code magic, can still always be accessed and modified. Other languages are stricter about this. Methods that are not private are termed ‘public’. Some other languages offer further levels of control (e.g., C++ allows for ‘protected’ variables and methods), Python does not.”
Nice work, I am sure many appreciate it.
This is a great resource for those with a request I see often on the forums, how to take what is learnt in the samples and manual and apply it to a “real game”.