Jan-10-2019, 01:08 AM
I've been working through an introductory python book. I've got quite a bit of experience coding in other languages, but am new to Python. My book seems to have some odd notions about when to make attributes private and suggests all changes to an object's attributes should be done through methods. That sounds pretty tedious to me (creating all the accessors) but I was hoping to get some idea of what the python world things of its advice. The book says:
I added the italics. Now most of this makes sense but I've never been told not to directly access an object's attributes. Like I said, creating accessors for every attribute seems extremely tedious. I an appreciate concealing the sausage factory of a class with privacy, but this seems a bit strong.
Any comments or documentation welcome.
Quote:Understanding When to Implement Privacy
So now that you know how to use privacy, should you make every attribute in every class private to protect them from the outside world? Well, no. Privacy is like a fine spice: Used sparingly, it can greatly improve what you're making. Make private any method you don't want a client to invoke. If it's critical that an attribute never be accessed directly by a client, you can make it private. But keep this to a minimum, as creating private attributes is rare in Python. The philosophy among programmers is to trust that clients will sue an object's methods and not directly alter its attributes.
When you write a class:
* Create methods so that clients won't need to directly access an object's attributes
* Use privacy only for those attributes and methods that are completely internal to the operation of objects.
*
When you use an object:
* Minimize the direct reading of an object's attributes
* Avoid directly altering an object's attributes
* Never directly access an object's private attributes or methods
I added the italics. Now most of this makes sense but I've never been told not to directly access an object's attributes. Like I said, creating accessors for every attribute seems extremely tedious. I an appreciate concealing the sausage factory of a class with privacy, but this seems a bit strong.
Any comments or documentation welcome.