Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using assignment as operator [duplicate]

Tags:

python

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?

like image 799
AlwaysLearning Avatar asked Oct 10 '21 11:10

AlwaysLearning


People also ask

Can assignment operator be used instead of copy constructors?

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.

How do you define copy assignment operator?

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&.

Does assignment operator create a deep copy?

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.

Is ++ an assignment operator?

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.


Video Answer


1 Answers

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>
like image 89
Mohammad Jafari Avatar answered Oct 17 '22 10:10

Mohammad Jafari