course_db = Course(title='Databases') course_db.save()
Coming from a C++ background, I would expect
(course_db = Course(title='Databases')) to behave like it would in C++, that is, assign
course_db and return the assigned object so that I can use it as part of a larger expression. For example, I would expect the following code to do the same thing as the code above:
(course_db = Course(title='Databases')).save()
This assumption got support from some quick Google searches using terms like "assignment operator in Python", e.g. this article. But when I tried this, I got a syntax error.
Why can't I do this in Python, and what can I do instead?
You should do some more research about the differences between statements and expressions in Python.
If you are using Python 3.8+, you can use the
In : class A: ...: def save(self): ...: return 1 ...: In : (a := A()).save() Out: 1 In : a Out: <__main__.A at 0x7f074e2ddaf0>