Dec-28-2023, 09:27 PM
(Dec-27-2023, 04:26 PM)Gribouillis Wrote:(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 ashidden_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 thePerson
object as the memberself.hidden_data
. When the code using this class callsp.username
, that value is returned by the property getter function. When the client code writesp.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 directlyp.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 statementself.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 variableself.hidden_data
.
hi
you have said that :
Quote: 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_dataI ran the code and I saw that it changed names to lowercase and this is done in setter. but i do not understand why __init__ uses the setter . can explain?