Python Forum
question about using setter, getter and _
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
question about using setter, getter and _
#3
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.
akbarza likes this post
Reply


Messages In This Thread
RE: question about using setter, getter and _ - by deanhystad - Dec-27-2023, 06:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python class doesn't invoke setter during __init__, not sure if's not supposed to? mtldvl 2 3,519 Dec-30-2021, 04:01 PM
Last Post: mtldvl
  how to use getter as argument in function nanok66 3 3,414 May-13-2020, 09:15 AM
Last Post: nanok66
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 3,120 May-11-2020, 07:22 PM
Last Post: nboweb
  Setter of class object maitreyaverma 1 2,511 Sep-28-2017, 06:15 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020