Dec-27-2023, 06:30 PM
(This post was last modified: Dec-27-2023, 06:30 PM by deanhystad.)
It is a Python coding convention that attribute names starting with an underscore should be treated as private, and code outside the class should not access these variables. Think of it as a warning:
"I cannot stop you from referencing this attribute, but directly accessing the attribute is not how the class is designed to work. I won't feel any remorse when I change the design of this class in the future and remove this attribute that I warned you against using."
In your example, _username should not be referenced outside of the class. if you set the Person's username using the _username attribute you could break the rule that usernames are all lowercase. If this caused problems elsewhere in the code it would be all your fault because you didn't follow the rules (conventions) for using the class.
You might also see variable/attribute names that end in an underscore. This convention is used when the name you want to use conflicts with a Python keyword, a built-in function (next_ is one I often use) or some other name defined in your module.
"I cannot stop you from referencing this attribute, but directly accessing the attribute is not how the class is designed to work. I won't feel any remorse when I change the design of this class in the future and remove this attribute that I warned you against using."
In your example, _username should not be referenced outside of the class. if you set the Person's username using the _username attribute you could break the rule that usernames are all lowercase. If this caused problems elsewhere in the code it would be all your fault because you didn't follow the rules (conventions) for using the class.
You might also see variable/attribute names that end in an underscore. This convention is used when the name you want to use conflicts with a Python keyword, a built-in function (next_ is one I often use) or some other name defined in your module.