Chapter 3: Encapsulation

Public or non-public?

face Josiah Wang

You might be wondering whether an attribute should be public or non-public when designing your class. PEP 8 actually has quite a lot to say about the topic.

In general, when you declare an attribute as public, it means that anybody can use it. In essence, you are committing to not changing the name of the attribute - imagine having everyone who use your class to change an attribute name! If you keep an attribute non-public, then you can change things as you see fit, since only you are supposed to have access to these attributes!

When you design a class, just think about how much you want to allow the outside world to read or write these attributes. If you are unsure, just keep them non-public.

For ‘simple’ attributes, you can keep them public (unless they should clearly not be public). As we have seen, it is quite easy to turn them into properties later if needed.

If you already know that you want to restrict access to the attributes, then make them non-public.

There is really no one-size-fits-all answer to this question. It sometimes helps to think of your classes as entities in the real world. For example, would a Person give others access to his or her heart? Or would you be able to change the value of a Car’s fuel indicator directly? Or does it change based on how full the tank is? The fuel indicator is likely best to be a read-only property.

As a final note, I have purposely left the topic of encapsulation till the end, as encapsulation is not strictly enforced in Python due to its “open” philosophy. If you were learning OOP in another language like Java/C++, then this would have been one of the earliest things I would have covered!