Consider:
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(title='Databases')
to 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?
The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space.
A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&.
Like the copy constructor, the assignment operator has to make a copy of an object. The default version makes a shallow copy. If a deep copy is desired for assignments on a user-defined type (e.g. a class), then the assignment operator should be overloaded for the class.
Assignment Operators in C/C++ Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value.
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 :=
operator:
In [1]: class A:
...: def save(self):
...: return 1
...:
In [2]: (a := A()).save()
Out[2]: 1
In [3]: a
Out[3]: <__main__.A at 0x7f074e2ddaf0>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With