I get a can't set attribute when using @property in python

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

Can't set attribute gets stuck

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!

Why getters and setters

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

I get a can't set attribute when using @property in python
When I get a chromedriver error in Selenium
I get a java.util.regex.PatternSyntaxException when splitting a string in PySpark
I checked the reference speed when using python list, dictionary, and set type in.
[Python] I want to get a common set between numpy
I made a quick feed reader using feedparser in Python
A memo when creating a directed graph using Graphviz in Python
Since Python 1.5 of Discord, I can't get a list of members
I tried "How to get a method decorated in Python"
I tried to make a stopwatch using tkinter in python
Precautions when using pit in Python
I made a Line-bot using Python!
I get a KeyError in pyclustering.xmeans
I can't install scikit-learn in Python
When using regular expressions in Python
When writing a program in Python
When I tried to scrape using requests in python, I was addicted to SSLError, so a workaround memo
Get Suica balance in Python (using libpafe)
I made a payroll program in Python!
Precautions when pickling a function in python
Write a short property definition in Python
How to get a stacktrace in python
Get Youtube data in Python using Youtube Data API
Scraping a website using JavaScript in Python
I can't get the element in Selenium!
Get a token for conoha in python
Draw a tree in Python 3 using graphviz
I created a password tool in Python.
Why can't I install matplotlib in python! !!
Where do I stop when I set a breakpoint in a function in GDB (x86)
I made a Discord bot in Python that translates when it reacts
How to get a value from a parameter store in lambda (using python)
I get a UnicodeDecodeError when trying to connect to oracle with python sqlalchemy
Set up a local web server in 30 seconds using python 3's http.server
A useful note when using Python for the first time in a while
I wrote FizzBuzz in python using a support vector machine (library LIVSVM).
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda
I get an error when I put a Python plugin in Visual Studio Code under the pyenv environment
When codec can't decode byte appears in python
Create a GIF file using Pillow in Python
[Python] Get the files in a folder with Python
A memo that I wrote a quicksort in Python
Get the caller of a function in Python
I want to create a window in Python
I tried playing a typing game in Python
I wrote a class in Python3 and Java
Set up a test SMTP server in Python.
[Memo] I tried a pivot table in Python
I get a UnicodeDecodeError when running with mod_wsgi
View drug reviews using a list in Python
I tried reading a CSV file using Python
Set up a simple SMTP server in Python
I tried adding a Python3 module in C
Get a glimpse of machine learning in Python
[Question] What happens when I use% in python?
Create a MIDI file in Python using pretty_midi
I wrote a Japanese parser in Japanese using pyparsing.
I made a Caesar cryptographic program in Python.
In the Chainer tutorial, I get an error when importing a package. (mock)
[Python] What to check when you get a Unicode Decode Error in Django
What I do when imitating embedded go in python