I'm a person who writes code in python
However, since I am still a beginner, I often get bored with errors. Among them, I am writing this time with the intention of re-learning the setters and getters of the class that I have left unclear until now. Let's go!
python 3.7.4
There are times when you want to get what the class generated. What would you do in such a case?
practice01.py
class C(object):
def __init__(self) -> None:
self.x = 1
c = C()
r = c.x
print(r)
# 1
It's easy to write. But you want to use @property or something.
practice02.py
class C(object):
def __init__(self) -> None:
self.x = 1
@property
def x(self):
if self.x is None:
return None
return self.x
c = C()
r = c.x
print(r)
# AttributeError: can't set attribute
Yes, I got ʻAttributeError: can't set attribute`. So, I would like to present a solution first.
practice03.py
class C(object):
def __init__(self) -> None:
self._x = 1
@property
def x(self):
if self._x is None:
return None
return self._x
c = C()
r = c.x
print(r)
# 1
So why doesn't practice02.py
work?
That's because the variable name and the function name match. In other words, if you give the variable as self._x
like practice03.py
, it is safe because the __variable name and the function name are different __.
And in practice03.py
getter.py
@property
def x(self):
if self._x is None:
return None
return self._x
The part is called a getter!
In the case of a simple one like this article, I think it is easier to understand if you write it without using getters or setters. I think it's actually used when you want to treat a method that exists in the __ class like an attribute __.
There is a very helpful article, so I will refer to it.
I don't understand the need for the python3 property.
As you can see from this article, getters and setters are probably one of the techniques / techniques used when you want to make it easier to understand. ~~ In other words, it's a mood. ~~ If you can use it well, you will be able to write cleaner and easier-to-understand code! !! I will do my best to study so that I can use it well!
Someone wrote something easy to understand in the comment section, so please have a look there as well!
Then!
Recommended Posts