Dec-27-2023, 04:26 PM
(This post was last modified: Dec-27-2023, 04:26 PM by Gribouillis.)
(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
.
« We can solve any problem by introducing an extra level of indirection »