Nov-09-2020, 04:47 PM
I had no intention to go into details about properties/setters, but maybe it's worth a bit of explaining
Let's say we have class
We can add a third attribute, just the same like the other two. However to have consistency we can do
If you run the snippet you can see we are not able to change
Let's say we have class
Person
. It has two attributes which we pass when instantiate itclass Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name person = Person('John', 'Doe') print(person.first_name) print(person.last_name)What if we want a third attribute
name
that is the full name, i.e. <first_name> <last_name>
- John Doe
.We can add a third attribute, just the same like the other two. However to have consistency we can do
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def name(self): return f'{self.first_name} {self.last_name}' person = Person('John', 'Doe') print(person.first_name) print(person.last_name) print(person.name) person.name = 'Jack Ryan'
If you run the snippet you can see we are not able to change
name
(it raise error). To be able to change it, we can define setter for name
. Again, for consistency we need to change also first_name
and/or last_name
when we change name
, e.g.class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def name(self): return f'{self.first_name} {self.last_name}' @name.setter def name(self, value): self.first_name, *_, self.last_name = value.split(' ') person = Person('John', 'Doe') print(person.first_name) print(person.last_name) print(person.name) person.name = 'Jack Ryan' print(person.first_name) print(person.last_name) print(person.name)
Output:John
Doe
John Doe
Jack
Ryan
Jack Ryan
This is just a basic example, in other cases you may need to use "private" variable, that is considered "for internal use" and it is designated by single underscore, e.g. _some_name
. This is not really private variable like in other languages, just by convention "for internal use".
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs