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 _
#2
(Dec-27-2023, 01:20 PM)akbarza Wrote: what is differnce between username and _username or between self.username and slef._username?
_username is just another attribute name. It could be replaced by any other name such as hidden_data
class Person:
    def __init__(self,username):
        self.username=username
    #getter
    @property
    def username(self):
        return self.hidden_data

    #setter
    @username.setter
    def username(self,name):
        if not isinstance(name,str):
            raise TypeError('name must be a string')
        self.hidden_data= name.lower()


p=Person('Ali')
print(p.username)
# output will be : 'ali'
p.username='mohammad'
print(p.username)
#output will be: 'mohammad'
In this code, the name is stored in the Person object as the member self.hidden_data. When the code using this class calls p.username, that value is returned by the property getter function. When the client code writes p.username = 'Mohammad' the value is converted to lower case and then stored in the object by the property setter function.

Client code is not supposed to access directly p.hidden_data, but the Python language does not forbid that. Therefore it is a convention among Python programmers that a variable which name starts with an underscore is not meant to be accessed directly by client code. It is a "private" variable known from the Person class but not from client code. That's why a name such as _hidden_data or _username is preferred.

Note that the statement self.username = username in the __init__() function invokes the property setter to check that the argument is a string and to store the lowercase value of this argument in the variable self.hidden_data.
akbarza likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply


Messages In This Thread
RE: question about using setter, getter and _ - by Gribouillis - Dec-27-2023, 04:26 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,500 Dec-30-2021, 04:01 PM
Last Post: mtldvl
  how to use getter as argument in function nanok66 3 3,408 May-13-2020, 09:15 AM
Last Post: nanok66
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 3,112 May-11-2020, 07:22 PM
Last Post: nboweb
  Setter of class object maitreyaverma 1 2,506 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